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
6bc9088608c902dfd5d63f91e3b1b9f0c7d61796
src/util.ads
src/util.ads
----------------------------------------------------------------------- -- Util -- Various Utility Packages -- Copyright (C) 2001, 2002, 2003, 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. ----------------------------------------------------------------------- package Util is pragma Pure; -- Library SVN identification SVN_URL : constant String := "https://ada-util.googlecode.com/svn/trunk"; -- Revision used (must run 'make version' to update) SVN_REV : constant Positive := 723; end Util;
----------------------------------------------------------------------- -- util -- Various Utility Packages -- Copyright (C) 2001, 2002, 2003, 2009, 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 Util is pragma Pure; -- Library SVN identification SVN_URL : constant String := "https://ada-util.googlecode.com/svn/trunk"; -- Revision used (must run 'make version' to update) SVN_REV : constant Positive := 723; end Util;
Update the header
Update the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
45b018c499f2ace811532bac1f63d37885924ae7
src/wiki.ads
src/wiki.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- 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 Wiki is pragma Pure; end Wiki;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki is pragma Pure; type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT); type Format_Map is array (Format_Type) of Boolean; end Wiki;
Declare Format_Type and Format_Map
Declare Format_Type and Format_Map
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b34948c334bddd4971a67dcc02b1d4aac40a01c1
mat/src/mat-readers-streams.ads
mat/src/mat-readers-streams.ads
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- 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.Streams.Buffered; package MAT.Readers.Streams is type Stream_Reader_Type is new Manager_Base with private; -- Read the events from the stream and stop when the end of the stream is reached. procedure Read_All (Reader : in out Stream_Reader_Type); private type Stream_Reader_Type is new Manager_Base with record Stream : Util.Streams.Buffered.Buffered_Stream; end record; end MAT.Readers.Streams;
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- 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.Streams.Buffered; package MAT.Readers.Streams is type Stream_Reader_Type is new Manager_Base with private; -- Read the events from the stream and stop when the end of the stream is reached. procedure Read_All (Reader : in out Stream_Reader_Type); -- Read a message from the stream. overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message); private type Stream_Reader_Type is new Manager_Base with record Stream : Util.Streams.Buffered.Buffered_Stream; end record; end MAT.Readers.Streams;
Declare the Read_Message procedure
Declare the Read_Message procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1d20494198f7bd23fc64c2cb7337212be419b43b
src/gen-commands-page.adb
src/gen-commands-page.adb
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with Util.Strings.Transforms; package body Gen.Commands.Page is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Strings.Unbounded; function Get_Layout return String; Name : constant String := Get_Argument; Dir : constant String := Generator.Get_Result_Directory & "web/"; function Get_Layout return String is Layout : constant String := Get_Argument; begin if Layout'Length = 0 then return "layout"; end if; if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout); return "layout"; end Get_Layout; Layout : constant String := Get_Layout; begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); Generator.Set_Global ("pageName", Name); Generator.Set_Global ("layout", Layout); Generator.Set_Global ("projectCode", Util.Strings.Transforms.To_Upper_Case (Name)); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Text_IO; use Ada.Directories; Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts"; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Search : Search_Type; Ent : Directory_Entry_Type; begin Put_Line ("add-page: Add a new web page to the application"); Put_Line ("Usage: add-page NAME [LAYOUT]"); New_Line; Put_Line (" The new web page can be configured to use the given layout."); Put_Line (" The layout file must exist to be used. The default layout is 'layout'."); Put_Line (" You can create a new layout with 'add-layout' command."); Put_Line (" You can also write your layout by adding an XHTML file in the directory:"); Put_Line (" " & Path); if Exists (Path) then New_Line; Put_Line (" Available layouts:"); Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Layout : constant String := Base_Name (Name); begin Put_Line (" " & Layout); end; end loop; end if; end Help; end Gen.Commands.Page;
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- 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.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; package body Gen.Commands.Page is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Strings.Unbounded; function Get_Layout return String; Name : constant String := Get_Argument; Dir : constant String := Generator.Get_Result_Directory & "web/"; function Get_Layout return String is Layout : constant String := Get_Argument; begin if Layout'Length = 0 then return "layout"; end if; if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout); return "layout"; end Get_Layout; Layout : constant String := Get_Layout; begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); Generator.Set_Global ("pageName", Name); Generator.Set_Global ("layout", Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Text_IO; use Ada.Directories; Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts"; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Search : Search_Type; Ent : Directory_Entry_Type; begin Put_Line ("add-page: Add a new web page to the application"); Put_Line ("Usage: add-page NAME [LAYOUT]"); New_Line; Put_Line (" The new web page can be configured to use the given layout."); Put_Line (" The layout file must exist to be used. The default layout is 'layout'."); Put_Line (" You can create a new layout with 'add-layout' command."); Put_Line (" You can also write your layout by adding an XHTML file in the directory:"); Put_Line (" " & Path); if Exists (Path) then New_Line; Put_Line (" Available layouts:"); Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Layout : constant String := Base_Name (Name); begin Put_Line (" " & Layout); end; end loop; end if; end Help; end Gen.Commands.Page;
Remove projectCode global
Remove projectCode global
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
802b20f2784c9ef57606c6535948c829ba71259a
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Log.Loggers; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is use type ADO.Identifier; Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); if Part.Get_Size > 100_000 then Manager.Save (Bean, Part, AWA.Storages.Models.FILE); else Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end if; exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Storages.Models.Query_Storage_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Storage_Bean bean instance. -- ------------------------------ function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_Bean_Access := new Storage_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Storage_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Log.Loggers; with Util.Strings; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is use type ADO.Identifier; Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); if Part.Get_Size > 100_000 then Manager.Save (Bean, Part, AWA.Storages.Models.FILE); else Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end if; exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; -- ------------------------------ -- Returns true if the given mime type can be displayed by a browser. -- Mime types: application/pdf, text/*, image/* -- ------------------------------ function Is_Browser_Visible (Mime_Type : in String) return Boolean is begin if Mime_Type = "application/pdf" then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "text/") then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "image/") then return True; end if; return False; end Is_Browser_Visible; overriding function Get_Value (From : in Storage_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "isBrowserVisible" then return Util.Beans.Objects.To_Object (Is_Browser_Visible (To_String (From.Mime_Type))); else return AWA.Storages.Models.Storage_Bean (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Storages.Models.Query_Storage_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Storage_Bean bean instance. -- ------------------------------ function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_Bean_Access := new Storage_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Storage_Bean; end AWA.Storages.Beans;
Implement Is_Browser_Visible and Get_Value for Storage_Bean
Implement Is_Browser_Visible and Get_Value for Storage_Bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6abe6d183d8756c8af4df2044d086c29ba117314
awa/plugins/awa-images/src/awa-images-modules.ads
awa/plugins/awa-images/src/awa-images-modules.ads
----------------------------------------------------------------------- -- 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 ASF.Applications; with AWA.Modules; with AWA.Storages.Models; with AWA.Storages.Services; with AWA.Images.Services; -- == Image Module == -- The <tt>Image_Module</tt> type represents the image module. An instance of the image -- module must be declared and registered when the application is created and initialized. -- The image module is associated with the image service which provides and implements -- the image management operations. -- -- When the image module is initialized, it registers itself as a listener to the storage -- module to be notified when a storage file is created, updated or removed. When a file -- is added, it looks at the file type and extracts the image information if the storage file -- is an image. package AWA.Images.Modules is NAME : constant String := "images"; type Image_Module is new AWA.Modules.Module and AWA.Storages.Services.Listener with private; type Image_Module_Access is access all Image_Module'Class; -- Initialize the image module. overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config); -- Get the image manager. function Get_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access; -- 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; -- 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); -- 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); -- 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); -- Get the image module instance associated with the current application. function Get_Image_Module return Image_Module_Access; -- Get the image manager instance associated with the current application. function Get_Image_Manager return Services.Image_Service_Access; -- Returns true if the storage file has an image mime type. function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean; private type Image_Module is new AWA.Modules.Module and AWA.Storages.Services.Listener with record Manager : Services.Image_Service_Access := null; end record; 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 ASF.Applications; with AWA.Modules; with AWA.Storages.Models; with AWA.Storages.Services; with AWA.Images.Services; with AWA.Images.Models; with AWA.Jobs.Services; with AWA.Jobs.Modules; -- == Image Module == -- The <tt>Image_Module</tt> type represents the image module. An instance of the image -- module must be declared and registered when the application is created and initialized. -- The image module is associated with the image service which provides and implements -- the image management operations. -- -- When the image module is initialized, it registers itself as a listener to the storage -- module to be notified when a storage file is created, updated or removed. When a file -- is added, it looks at the file type and extracts the image information if the storage file -- is an image. package AWA.Images.Modules is NAME : constant String := "images"; -- Job worker procedure to identify an image and generate its thumnbnail. procedure Thumbnail_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class); package Thumbnail_Job_Definition is new AWA.Jobs.Services.Work_Definition (Thumbnail_Worker'Access); type Image_Module is new AWA.Modules.Module and AWA.Storages.Services.Listener with private; type Image_Module_Access is access all Image_Module'Class; -- Initialize the image module. overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config); -- Get the image manager. function Get_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access; -- 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; -- 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); -- 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); -- 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); -- Create a thumbnail job for the image. procedure Make_Thumbnail_Job (Plugin : in Image_Module; Image : in AWA.Images.Models.Image_Ref'Class); -- 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); -- Get the image module instance associated with the current application. function Get_Image_Module return Image_Module_Access; -- Get the image manager instance associated with the current application. function Get_Image_Manager return Services.Image_Service_Access; -- Returns true if the storage file has an image mime type. function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean; private type Image_Module is new AWA.Modules.Module and AWA.Storages.Services.Listener with record Manager : Services.Image_Service_Access := null; Job_Module : AWA.Jobs.Modules.Job_Module_Access; end record; -- Create an image instance. procedure Create_Image (Plugin : in Image_Module; File : in AWA.Storages.Models.Storage_Ref'Class); end AWA.Images.Modules;
Declare the Thumbnail_Worker procedure and the Thumbnail_Job_Definition job Declare Make_Thumbnail_Job and Do_Thumbnail_Job procedures Declare Create_Image procedure
Declare the Thumbnail_Worker procedure and the Thumbnail_Job_Definition job Declare Make_Thumbnail_Job and Do_Thumbnail_Job procedures Declare Create_Image procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
366fc4fa12b4069f0ab09a1cdbf2595cedde6898
awa/awaunit/awa-tests.adb
awa/awaunit/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with ASF.Server.Web; with ASF.Converters.Dates; with ASF.Tests; with AWA.Users.Module; with AWA.Mail.Module; with AWA.Blogs.Module; with AWA.Workspaces.Module; -- with AWA.Applications; with AWA.Applications.Factory; with AWA.Services.Filters; package body AWA.Tests is protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Users : aliased AWA.Users.Module.User_Module; Workspaces : aliased AWA.Workspaces.Module.Workspace_Module; Mail : aliased AWA.Mail.Module.Mail_Module; Blogs : aliased AWA.Blogs.Module.Blog_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new AWA.Applications.Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); if Add_Modules then declare Users : constant AWA.Users.Module.User_Module_Access := AWA.Tests.Users'Access; begin Register (App => Application.all'Access, Name => AWA.Users.Module.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Module.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with ASF.Server.Web; with ASF.Converters.Dates; with ASF.Tests; with AWA.Users.Module; with AWA.Mail.Module; with AWA.Blogs.Module; with AWA.Workspaces.Module; with AWA.Storages.Modules; -- with AWA.Applications; with AWA.Applications.Factory; with AWA.Services.Filters; package body AWA.Tests is protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Users : aliased AWA.Users.Module.User_Module; Workspaces : aliased AWA.Workspaces.Module.Workspace_Module; Mail : aliased AWA.Mail.Module.Mail_Module; Blogs : aliased AWA.Blogs.Module.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new AWA.Applications.Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); if Add_Modules then declare Users : constant AWA.Users.Module.User_Module_Access := AWA.Tests.Users'Access; begin Register (App => Application.all'Access, Name => AWA.Users.Module.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Module.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; end AWA.Tests;
Add the storage module in the unit tests
Add the storage module in the unit tests
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
58002862d2a941a6ecef9064a11b630b8194f666
awa/plugins/awa-storages/src/awa-storages-servlets.adb
awa/plugins/awa-storages/src/awa-storages-servlets.adb
----------------------------------------------------------------------- -- awa-storages-servlets -- Serve files saved in the storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with ADO.Objects; with ASF.Streams; with AWA.Storages.Services; with AWA.Storages.Modules; package body AWA.Storages.Servlets is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Servlets"); -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ overriding procedure Initialize (Server : in out Storage_Servlet; Context : in ASF.Servlets.Servlet_Registry'Class) is begin null; end Initialize; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ overriding procedure Do_Get (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Data : ADO.Blob_Ref; Mime : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; begin Storage_Servlet'Class (Server).Load (Request, Name, Mime, Date, Data); if Data.Is_Null then Log.Info ("Storage file {0} not found", Request.Get_Request_URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end if; -- Send the file. Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime)); if Ada.Strings.Unbounded.Length (Name) > 0 then Response.Add_Header ("Content-Disposition", "attachment; filename=" & Ada.Strings.Unbounded.To_String (Name)); end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write (Data.Value.Data); end; exception when ADO.Objects.NOT_FOUND | Constraint_Error => Log.Info ("Storage file {0} not found", Request.Get_Request_URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end Do_Get; -- ------------------------------ -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. -- ------------------------------ procedure Load (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref) is pragma Unreferenced (Server); Store : constant String := Request.Get_Path_Parameter (1); Manager : constant Services.Storage_Service_Access := Storages.Modules.Get_Storage_Manager; Id : ADO.Identifier; begin if Store'Length = 0 then Log.Info ("Invalid storage URI: {0}", Store); return; end if; -- Extract the storage identifier from the URI. Id := ADO.Identifier'Value (Store); Log.Info ("GET storage file {0}", Store); Manager.Load (From => Id, Name => Name, Mime => Mime, Date => Date, Into => Data); end Load; end AWA.Storages.Servlets;
----------------------------------------------------------------------- -- awa-storages-servlets -- Serve files saved in the storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with ADO.Objects; with ASF.Streams; with AWA.Storages.Services; with AWA.Storages.Modules; package body AWA.Storages.Servlets is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Servlets"); -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ overriding procedure Initialize (Server : in out Storage_Servlet; Context : in Servlet.Core.Servlet_Registry'Class) is begin null; end Initialize; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ overriding procedure Do_Get (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Data : ADO.Blob_Ref; Mime : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; Date : Ada.Calendar.Time; begin Storage_Servlet'Class (Server).Load (Request, Name, Mime, Date, Data); if Data.Is_Null then Log.Info ("Storage file {0} not found", Request.Get_Request_URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end if; -- Send the file. Response.Set_Content_Type (Ada.Strings.Unbounded.To_String (Mime)); if Ada.Strings.Unbounded.Length (Name) > 0 then Response.Add_Header ("Content-Disposition", "attachment; filename=" & Ada.Strings.Unbounded.To_String (Name)); end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write (Data.Value.Data); end; exception when ADO.Objects.NOT_FOUND | Constraint_Error => Log.Info ("Storage file {0} not found", Request.Get_Request_URI); Response.Send_Error (ASF.Responses.SC_NOT_FOUND); return; end Do_Get; -- ------------------------------ -- Load the data content that correspond to the GET request and get the name as well -- as mime-type and date. -- ------------------------------ procedure Load (Server : in Storage_Servlet; Request : in out ASF.Requests.Request'Class; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Data : out ADO.Blob_Ref) is pragma Unreferenced (Server); Store : constant String := Request.Get_Path_Parameter (1); Manager : constant Services.Storage_Service_Access := Storages.Modules.Get_Storage_Manager; Id : ADO.Identifier; begin if Store'Length = 0 then Log.Info ("Invalid storage URI: {0}", Store); return; end if; -- Extract the storage identifier from the URI. Id := ADO.Identifier'Value (Store); Log.Info ("GET storage file {0}", Store); Manager.Load (From => Id, Name => Name, Mime => Mime, Date => Date, Into => Data); end Load; end AWA.Storages.Servlets;
Use the Servlet.Core package instread of ASF.Servlets
Use the Servlet.Core package instread of ASF.Servlets
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
02fa6d0e4ddf936995fd8ca5b7632aa48776e18e
src/asf-views-facelets.adb
src/asf-views-facelets.adb
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ASF.Views.Nodes.Reader; with Input_Sources.File; with Sax.Readers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; package body ASF.Views.Facelets is use ASF.Views.Nodes; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info, Name => ASF.Views.File_Info_Access); -- Find in the factory for the facelet with the given name. procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet); -- Load the facelet node tree by reading the facelet XHTML file. procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Update the factory to store the facelet node tree procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet); -- ------------------------------ -- Returns True if the facelet is null/empty. -- ------------------------------ function Is_Null (F : Facelet) return Boolean is begin return F.Root = null; end Is_Null; -- ------------------------------ -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. -- ------------------------------ procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Res : Facelet; Fname : constant Unbounded_String := To_Unbounded_String (Name); begin Log.Debug ("Find facelet {0}", Name); Find (Factory, Fname, Res); if Res.Root = null then Load (Factory, Name, Context, Res); if Res.Root = null then Result.Root := null; return; end if; Update (Factory, Fname, Res); end if; Result.Root := Res.Root; Result.File := Res.File; end Find_Facelet; -- ------------------------------ -- Create the component tree from the facelet view. -- ------------------------------ procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access) is Old : Unbounded_String; begin if View.Root /= null then Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.File.all), Previous => Old); View.Root.Build_Children (Parent => Root, Context => Context); Context.Set_Relative_Path (Path => Old); end if; end Build_View; -- ------------------------------ -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. -- ------------------------------ procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean) is begin Log.Info ("Set facelet search directory to: '{0}'", Paths); Factory.Factory := Components; Factory.Paths := To_Unbounded_String (Paths); Factory.Ignore_White_Spaces := Ignore_White_Spaces; Factory.Ignore_Empty_Lines := Ignore_Empty_Lines; Factory.Escape_Unknown_Tags := Escape_Unknown_Tags; end Initialize; -- ------------------------------ -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. -- ------------------------------ function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String is begin return Util.Files.Find_File_Path (Name, To_String (Factory.Paths)); end Find_Facelet_Path; -- ------------------------------ -- Find in the factory for the facelet with the given name. -- ------------------------------ procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet) is use Ada.Directories; use Ada.Calendar; begin Result.Root := null; Result := Factory.Map.Find (Name); if Result.Root /= null and then Modification_Time (Result.File.Path) > Result.Modify_Time then Result.Root := null; Log.Info ("Ignoring cache because file '{0}' was modified", Result.File.Path); end if; end Find; -- ------------------------------ -- Load the facelet node tree by reading the facelet XHTML file. -- ------------------------------ procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Path : constant String := Find_Facelet_Path (Factory, Name); begin if not Ada.Directories.Exists (Path) then Log.Warn ("Cannot read '{0}': file does not exist", Path); Result.Root := null; return; end if; declare RPos : constant Natural := Path'Length - Name'Length + 1; File : File_Info_Access := Create_File_Info (Path, RPos); Reader : ASF.Views.Nodes.Reader.Xhtml_Reader; Read : Input_Sources.File.File_Input; Mtime : Ada.Calendar.Time; Ctx : aliased EL.Contexts.Default.Default_Context; begin Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name, Natural'Image (File.Relative_Pos)); Ctx.Set_Function_Mapper (Context.Get_Function_Mapper); Mtime := Ada.Directories.Modification_Time (Path); Input_Sources.File.Open (Path, Read); -- If True, xmlns:* attributes will be reported in Start_Element Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False); Reader.Set_Feature (Sax.Readers.Validation_Feature, False); Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces); Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags); Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines); begin Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access); exception when ASF.Views.Nodes.Reader.Parsing_Error => Free (File); when E : others => Free (File); Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path, Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); end; Result.Root := Reader.Get_Root; Result.File := File; if File = null then if Result.Root /= null then Result.Root.Delete; end if; Result.Root := null; else Result.Modify_Time := Mtime; end if; Input_Sources.File.Close (Read); end; end Load; -- ------------------------------ -- Update the factory to store the facelet node tree -- ------------------------------ procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet) is begin Factory.Map.Insert (Name, Item); end Update; -- ------------------------------ -- Clear the facelet cache -- ------------------------------ procedure Clear_Cache (Factory : in out Facelet_Factory) is begin Log.Info ("Clearing facelet cache"); Factory.Map.Clear; end Clear_Cache; protected body Facelet_Cache is -- ------------------------------ -- Find the facelet entry associated with the given name. -- ------------------------------ function Find (Name : in Unbounded_String) return Facelet is Pos : constant Facelet_Maps.Cursor := Map.Find (Name); begin if Facelet_Maps.Has_Element (Pos) then return Element (Pos); else return Empty; end if; end Find; -- ------------------------------ -- Insert or replace the facelet entry associated with the given name. -- ------------------------------ procedure Insert (Name : in Unbounded_String; Item : in Facelet) is begin Map.Include (Name, Item); end Insert; -- ------------------------------ -- Clear the cache. -- ------------------------------ procedure Clear is begin loop declare Pos : Facelet_Maps.Cursor := Map.First; Node : Facelet; begin exit when not Has_Element (Pos); Node := Element (Pos); Map.Delete (Pos); Free (Node.File); ASF.Views.Nodes.Destroy (Node.Root); end; end loop; end Clear; end Facelet_Cache; -- ------------------------------ -- Free the storage held by the factory cache. -- ------------------------------ overriding procedure Finalize (Factory : in out Facelet_Factory) is begin Factory.Clear_Cache; end Finalize; end ASF.Views.Facelets;
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010, 2011, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Directories; with Ada.Unchecked_Deallocation; with ASF.Views.Nodes.Reader; with Input_Sources.File; with Sax.Readers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; package body ASF.Views.Facelets is use ASF.Views.Nodes; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Views.Facelets"); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Views.File_Info, Name => ASF.Views.File_Info_Access); -- Find in the factory for the facelet with the given name. procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet); -- Load the facelet node tree by reading the facelet XHTML file. procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Update the factory to store the facelet node tree procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet); -- ------------------------------ -- Returns True if the facelet is null/empty. -- ------------------------------ function Is_Null (F : Facelet) return Boolean is begin return F.Root = null; end Is_Null; -- ------------------------------ -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. -- ------------------------------ procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Res : Facelet; Fname : constant Unbounded_String := To_Unbounded_String (Name); begin Log.Debug ("Find facelet {0}", Name); Find (Factory, Fname, Res); if Res.Root = null then Load (Factory, Name, Context, Res); if Res.Root = null then Result.Root := null; return; end if; Update (Factory, Fname, Res); end if; Result.Root := Res.Root; Result.File := Res.File; end Find_Facelet; -- ------------------------------ -- Create the component tree from the facelet view. -- ------------------------------ procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.Base.UIComponent_Access) is Old : Unbounded_String; begin if View.Root /= null then Context.Set_Relative_Path (Path => ASF.Views.Relative_Path (View.File.all), Previous => Old); View.Root.Build_Children (Parent => Root, Context => Context); Context.Set_Relative_Path (Path => Old); end if; end Build_View; -- ------------------------------ -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. -- ------------------------------ procedure Initialize (Factory : in out Facelet_Factory; Components : access ASF.Factory.Component_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean) is begin Log.Info ("Set facelet search directory to: '{0}'", Paths); Factory.Factory := Components; Factory.Paths := To_Unbounded_String (Paths); Factory.Ignore_White_Spaces := Ignore_White_Spaces; Factory.Ignore_Empty_Lines := Ignore_Empty_Lines; Factory.Escape_Unknown_Tags := Escape_Unknown_Tags; end Initialize; -- ------------------------------ -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. -- ------------------------------ function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String is begin return Util.Files.Find_File_Path (Name, To_String (Factory.Paths)); end Find_Facelet_Path; -- ------------------------------ -- Find in the factory for the facelet with the given name. -- ------------------------------ procedure Find (Factory : in out Facelet_Factory; Name : in Unbounded_String; Result : out Facelet) is use Ada.Directories; use Ada.Calendar; begin Result.Root := null; Result := Factory.Map.Find (Name); if Result.Root /= null and then Modification_Time (Result.File.Path) > Result.Modify_Time then Result.Root := null; Log.Info ("Ignoring cache because file '{0}' was modified", Result.File.Path); end if; end Find; -- ------------------------------ -- Load the facelet node tree by reading the facelet XHTML file. -- ------------------------------ procedure Load (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet) is Path : constant String := Find_Facelet_Path (Factory, Name); begin if Path = "" or else not Ada.Directories.Exists (Path) then Log.Warn ("Cannot read '{0}': file does not exist", Path); Result.Root := null; return; end if; declare RPos : constant Integer := Path'Last - Name'Length + 1; File : File_Info_Access; Reader : ASF.Views.Nodes.Reader.Xhtml_Reader; Read : Input_Sources.File.File_Input; Mtime : Ada.Calendar.Time; Ctx : aliased EL.Contexts.Default.Default_Context; begin if Rpos <= Path'First then File := Create_File_Info (Path, Path'First); else File := Create_File_Info (Path, RPos); end if; Log.Info ("Loading facelet: '{0}' - {1} - {2}", Path, Name, Natural'Image (File.Relative_Pos)); Ctx.Set_Function_Mapper (Context.Get_Function_Mapper); Mtime := Ada.Directories.Modification_Time (Path); Input_Sources.File.Open (Path, Read); -- If True, xmlns:* attributes will be reported in Start_Element Reader.Set_Feature (Sax.Readers.Namespace_Prefixes_Feature, False); Reader.Set_Feature (Sax.Readers.Validation_Feature, False); Reader.Set_Ignore_White_Spaces (Factory.Ignore_White_Spaces); Reader.Set_Escape_Unknown_Tags (Factory.Escape_Unknown_Tags); Reader.Set_Ignore_Empty_Lines (Factory.Ignore_Empty_Lines); begin Reader.Parse (File, Read, Factory.Factory, Ctx'Unchecked_Access); exception when ASF.Views.Nodes.Reader.Parsing_Error => Free (File); when E : others => Free (File); Log.Error ("Unexpected exception while reading: '{0}': {1}: {2}", Path, Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); end; Result.Root := Reader.Get_Root; Result.File := File; if File = null then if Result.Root /= null then Result.Root.Delete; end if; Result.Root := null; else Result.Modify_Time := Mtime; end if; Input_Sources.File.Close (Read); end; end Load; -- ------------------------------ -- Update the factory to store the facelet node tree -- ------------------------------ procedure Update (Factory : in out Facelet_Factory; Name : in Unbounded_String; Item : in Facelet) is begin Factory.Map.Insert (Name, Item); end Update; -- ------------------------------ -- Clear the facelet cache -- ------------------------------ procedure Clear_Cache (Factory : in out Facelet_Factory) is begin Log.Info ("Clearing facelet cache"); Factory.Map.Clear; end Clear_Cache; protected body Facelet_Cache is -- ------------------------------ -- Find the facelet entry associated with the given name. -- ------------------------------ function Find (Name : in Unbounded_String) return Facelet is Pos : constant Facelet_Maps.Cursor := Map.Find (Name); begin if Facelet_Maps.Has_Element (Pos) then return Element (Pos); else return Empty; end if; end Find; -- ------------------------------ -- Insert or replace the facelet entry associated with the given name. -- ------------------------------ procedure Insert (Name : in Unbounded_String; Item : in Facelet) is begin Map.Include (Name, Item); end Insert; -- ------------------------------ -- Clear the cache. -- ------------------------------ procedure Clear is begin loop declare Pos : Facelet_Maps.Cursor := Map.First; Node : Facelet; begin exit when not Has_Element (Pos); Node := Element (Pos); Map.Delete (Pos); Free (Node.File); ASF.Views.Nodes.Destroy (Node.Root); end; end loop; end Clear; end Facelet_Cache; -- ------------------------------ -- Free the storage held by the factory cache. -- ------------------------------ overriding procedure Finalize (Factory : in out Facelet_Factory) is begin Factory.Clear_Cache; end Finalize; end ASF.Views.Facelets;
Fix path and relative path when loading a facelet file
Fix path and relative path when loading a facelet file
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
0981fcff160696f2c7b052ce779b48d71163dd36
regtests/util-strings-tests.ads
regtests/util-strings-tests.ads
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Escape_Java (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); procedure Test_Starts_With (T : in out Test); procedure Test_Ends_With (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); -- Test formatting strings. procedure Test_Format (T : in out Test); end Util.Strings.Tests;
----------------------------------------------------------------------- -- util-strings-tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Escape_Java (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); procedure Test_Starts_With (T : in out Test); procedure Test_Ends_With (T : in out Test); procedure Test_Replace (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); -- Test formatting strings. procedure Test_Format (T : in out Test); end Util.Strings.Tests;
Add Test_Replace procedure
Add Test_Replace procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
07b4c5f48eef3e0cf8e78874cbeb4f721071b753
src/sqlite/ado-drivers-connections-sqlite.ads
src/sqlite/ado-drivers-connections-sqlite.ads
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Create the database and initialize it with the schema SQL file. overriding procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- 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. overriding procedure Create_Database (D : in out Sqlite_Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); end ADO.Drivers.Connections.Sqlite;
Move the Create_Database operation on the Driver instead of the database connection
Move the Create_Database operation on the Driver instead of the database connection
Ada
apache-2.0
stcarrez/ada-ado
edbf54509db958ad24cd34e8a26f97a6d6eaabb1
awa/plugins/awa-storages/src/awa-storages-stores-databases.ads
awa/plugins/awa-storages/src/awa-storages-stores-databases.ads
----------------------------------------------------------------------- -- awa-storages-stores-databases -- Database store -- 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 ADO.Sessions; with AWA.Storages.Models; -- === Database store === -- The `AWA.Storages.Stores.Databases` store uses the database to save a data content. -- The data is saved in a specific table in a database blob column. -- The database store uses another store service to temporarily save the data content -- in a local file when the application needs a file access to the data. package AWA.Storages.Stores.Databases is -- ------------------------------ -- Storage Service -- ------------------------------ type Database_Store is new AWA.Storages.Stores.Store with record Tmp : AWA.Storages.Stores.Store_Access; end record; -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. procedure Save (Storage : in Database_Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String); procedure Load (Storage : in Database_Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File); -- Create a storage procedure Create (Storage : in Database_Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File); -- Delete the content associate with the storage represented by `From`. procedure Delete (Storage : in Database_Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class); end AWA.Storages.Stores.Databases;
----------------------------------------------------------------------- -- awa-storages-stores-databases -- Database store -- Copyright (C) 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 ADO.Sessions; with ASF.Applications.Main.Configs; with AWA.Storages.Models; -- === Database store === -- The `AWA.Storages.Stores.Databases` store uses the database to save a data content. -- The data is saved in a specific table in a database blob column. -- The database store uses another store service to temporarily save the data content -- in a local file when the application needs a file access to the data. package AWA.Storages.Stores.Databases is -- Parameter that indicates the maximum size of files stored in the database. package Max_Size_Parameter is new ASF.Applications.Main.Configs.Parameter (Name => "database_max_size", Default => "100000"); -- ------------------------------ -- Storage Service -- ------------------------------ type Database_Store is new AWA.Storages.Stores.Store with record Tmp : AWA.Storages.Stores.Store_Access; end record; -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. procedure Save (Storage : in Database_Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String); procedure Load (Storage : in Database_Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File); -- Create a storage procedure Create (Storage : in Database_Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File); -- Delete the content associate with the storage represented by `From`. procedure Delete (Storage : in Database_Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class); end AWA.Storages.Stores.Databases;
Add new Max_Size_Parameter configuration
Add new Max_Size_Parameter configuration
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
092865a1ed2e9b587b6784805a571d69df9546ec
src/util-streams-files.ads
src/util-streams-files.ads
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- Copyright (C) 2010, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Streams.Stream_IO; package Util.Streams.Files is -- ----------------------- -- File stream -- ----------------------- -- The <b>File_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type File_Stream is limited new Output_Stream and Input_Stream with private; -- Open the file and initialize the stream for reading or writing. procedure Open (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Create the file and initialize the stream for writing. procedure Create (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Close the stream. overriding procedure Close (Stream : in out File_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out File_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out File_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type File_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Ada.Streams.Stream_IO.File_Type; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out File_Stream); end Util.Streams.Files;
----------------------------------------------------------------------- -- Util.Streams.Files -- File Stream utilities -- Copyright (C) 2010, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Streams.Stream_IO; package Util.Streams.Files is pragma Preelaborate; -- ----------------------- -- File stream -- ----------------------- -- The <b>File_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type File_Stream is limited new Output_Stream and Input_Stream with private; -- Open the file and initialize the stream for reading or writing. procedure Open (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Create the file and initialize the stream for writing. procedure Create (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Close the stream. overriding procedure Close (Stream : in out File_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out File_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out File_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type File_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Ada.Streams.Stream_IO.File_Type; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out File_Stream); end Util.Streams.Files;
Add pragma Preelaborate for the Util.Streams.Files package
Add pragma Preelaborate for the Util.Streams.Files package
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a00908e637d957bdd727576d5d89d6932ea794bf
src/util-streams-pipes.ads
src/util-streams-pipes.ads
----------------------------------------------------------------------- -- util-streams-pipes -- Pipe stream to or from a process -- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Processes; -- == Pipes == -- The `Util.Streams.Pipes` package defines a pipe stream to or from a process. -- It allows to launch an external program while getting the program standard output or -- providing the program standard input. The `Pipe_Stream` type represents the input or -- output stream for the external program. This is a portable interface that works on -- Unix and Windows. -- -- The process is created and launched by the `Open` operation. The pipe allows -- to read or write to the process through the `Read` and `Write` operation. -- It is very close to the *popen* operation provided by the C stdio library. -- First, create the pipe instance: -- -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- -- The pipe instance can be associated with only one process at a time. -- The process is launched by using the `Open` command and by specifying the command -- to execute as well as the pipe redirection mode: -- -- * `READ` to read the process standard output, -- * `WRITE` to write the process standard input. -- -- For example to run the `ls -l` command and read its output, we could run it by using: -- -- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ); -- -- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the -- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads -- the pipe to fill the buffer. The initialization of the buffer is the following: -- -- with Util.Streams.Buffered; -- ... -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024); -- -- And to read the process output, one can use the following: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- ... -- Buffer.Read (Into => Content); -- -- The pipe object should be closed when reading or writing to it is finished. -- By closing the pipe, the caller will wait for the termination of the process. -- The process exit status can be obtained by using the `Get_Exit_Status` function. -- -- Pipe.Close; -- if Pipe.Get_Exit_Status /= 0 then -- Ada.Text_IO.Put_Line ("Command exited with status " -- & Integer'Image (Pipe.Get_Exit_Status)); -- end if; -- -- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied. -- When leaving the scope of the `Pipe_Stream` instance, the application will wait for -- the process to terminate. -- -- Before opening the pipe, it is possible to have some control on the process that -- will be created to configure: -- -- * The shell that will be used to launch the process, -- * The process working directory, -- * Redirect the process output to a file, -- * Redirect the process error to a file, -- * Redirect the process input from a file. -- -- All these operations must be made before calling the `Open` procedure. package Util.Streams.Pipes is use Util.Processes; subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE; -- ----------------------- -- Pipe stream -- ----------------------- -- The <b>Pipe_Stream</b> is an output/input stream that reads or writes -- to or from a process. type Pipe_Stream is limited new Output_Stream and Input_Stream with private; -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. procedure Set_Shell (Stream : in out Pipe_Stream; Shell : in String); -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. procedure Set_Working_Directory (Stream : in out Pipe_Stream; Path : in String); -- Closes the given file descriptor in the child process before executing the command. procedure Add_Close (Stream : in out Pipe_Stream; Fd : in Util.Processes.File_Type); -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ); -- Close the pipe and wait for the external process to terminate. overriding procedure Close (Stream : in out Pipe_Stream); -- Get the process exit status. function Get_Exit_Status (Stream : in Pipe_Stream) return Integer; -- Returns True if the process is running. function Is_Running (Stream : in Pipe_Stream) return Boolean; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record Proc : Util.Processes.Process; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Pipe_Stream); end Util.Streams.Pipes;
----------------------------------------------------------------------- -- util-streams-pipes -- Pipe stream to or from a process -- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Processes; -- == Pipes == -- The `Util.Streams.Pipes` package defines a pipe stream to or from a process. -- It allows to launch an external program while getting the program standard output or -- providing the program standard input. The `Pipe_Stream` type represents the input or -- output stream for the external program. This is a portable interface that works on -- Unix and Windows. -- -- The process is created and launched by the `Open` operation. The pipe allows -- to read or write to the process through the `Read` and `Write` operation. -- It is very close to the *popen* operation provided by the C stdio library. -- First, create the pipe instance: -- -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- -- The pipe instance can be associated with only one process at a time. -- The process is launched by using the `Open` command and by specifying the command -- to execute as well as the pipe redirection mode: -- -- * `READ` to read the process standard output, -- * `WRITE` to write the process standard input. -- -- For example to run the `ls -l` command and read its output, we could run it by using: -- -- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ); -- -- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the -- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads -- the pipe to fill the buffer. The initialization of the buffer is the following: -- -- with Util.Streams.Buffered; -- ... -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024); -- -- And to read the process output, one can use the following: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- ... -- Buffer.Read (Into => Content); -- -- The pipe object should be closed when reading or writing to it is finished. -- By closing the pipe, the caller will wait for the termination of the process. -- The process exit status can be obtained by using the `Get_Exit_Status` function. -- -- Pipe.Close; -- if Pipe.Get_Exit_Status /= 0 then -- Ada.Text_IO.Put_Line ("Command exited with status " -- & Integer'Image (Pipe.Get_Exit_Status)); -- end if; -- -- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied. -- When leaving the scope of the `Pipe_Stream` instance, the application will wait for -- the process to terminate. -- -- Before opening the pipe, it is possible to have some control on the process that -- will be created to configure: -- -- * The shell that will be used to launch the process, -- * The process working directory, -- * Redirect the process output to a file, -- * Redirect the process error to a file, -- * Redirect the process input from a file. -- -- All these operations must be made before calling the `Open` procedure. package Util.Streams.Pipes is use Util.Processes; subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE; -- ----------------------- -- Pipe stream -- ----------------------- -- The <b>Pipe_Stream</b> is an output/input stream that reads or writes -- to or from a process. type Pipe_Stream is limited new Output_Stream and Input_Stream with private; -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. procedure Set_Shell (Stream : in out Pipe_Stream; Shell : in String); -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. procedure Set_Working_Directory (Stream : in out Pipe_Stream; Path : in String); -- Closes the given file descriptor in the child process before executing the command. procedure Add_Close (Stream : in out Pipe_Stream; Fd : in Util.Processes.File_Type); -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ); -- Close the pipe and wait for the external process to terminate. overriding procedure Close (Stream : in out Pipe_Stream); -- Get the process exit status. function Get_Exit_Status (Stream : in Pipe_Stream) return Integer; -- Returns True if the process is running. function Is_Running (Stream : in Pipe_Stream) return Boolean; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record Proc : Util.Processes.Process; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Pipe_Stream); end Util.Streams.Pipes;
Remove unused use Ada.Streams clause reported by GNAT 2018
Remove unused use Ada.Streams clause reported by GNAT 2018
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
25b4c6603f7f340025504da9bf7520ceeeb61f1a
src/gen-commands-info.adb
src/gen-commands-info.adb
----------------------------------------------------------------------- -- gen-commands-info -- Collect and give information about the project -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Gen.Utils; with Gen.Utils.GNAT; with Gen.Model.Projects; with Util.Strings.Sets; with Util.Files; package body Gen.Commands.Info is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector); procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean); procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition); procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition); procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count); procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition); procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector); List : Gen.Utils.String_List.Vector; Names : Util.Strings.Sets.Set; procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector) is procedure Add_Model_Dir (Base_Dir : in String; Dir : in String); procedure Add_Model_Dir (Base_Dir : in String; Dir : in String) is Path : constant String := Util.Files.Compose (Base_Dir, Dir); begin if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then Result.Append (Path); end if; end Add_Model_Dir; Iter : Gen.Utils.String_List.Cursor := List.First; begin while Gen.Utils.String_List.Has_Element (Iter) loop declare Path : constant String := Gen.Utils.String_List.Element (Iter); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Add_Model_Dir (Dir, "db"); Add_Model_Dir (Dir, "db/regtests"); Add_Model_Dir (Dir, "db/samples"); end; Gen.Utils.String_List.Next (Iter); end loop; end Collect_Directories; procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean) is pragma Unreferenced (Name); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (File); Done := False; end Print_Model_File; -- ------------------------------ -- Print the list of GNAT projects used by the main project. -- ------------------------------ procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is use Gen.Utils.GNAT; Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First; Info : Project_Info; begin if Project_Info_Vectors.Has_Element (Iter) then Ada.Text_IO.Put_Line ("GNAT project files:"); while Project_Info_Vectors.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Info := Project_Info_Vectors.Element (Iter); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path)); Project_Info_Vectors.Next (Iter); end loop; end if; end Print_GNAT_Projects; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := List.First; Ref : Model.Projects.Project_Reference; begin while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name)); Ada.Text_IO.Set_Col (Indent + 30); if Ref.Project /= null then Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path)); else Ada.Text_IO.Put_Line ("?"); end if; Project_Vectors.Next (Iter); end loop; end Print_Project_List; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := Project.Modules.First; Ref : Model.Projects.Project_Reference; begin if not Project.Modules.Is_Empty then Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put_Line ("Dynamo plugins:"); Print_Project_List (Indent, Project.Modules); Print_Project_List (Indent, Project.Dependencies); Iter := Project.Modules.First; while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then declare Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name); begin Ada.Text_IO.Set_Col (Indent); if Names.Contains (Name) then Ada.Text_IO.Put_Line ("!! " & Name); else Names.Insert (Name); Ada.Text_IO.Put_Line ("== " & Name); Print_Modules (Ref.Project.all, Indent + 4); Names.Delete (Name); end if; end; end if; Project_Vectors.Next (Iter); end loop; end if; end Print_Modules; -- ------------------------------ -- Print the list of Dynamo projects used by the main project. -- ------------------------------ procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First; begin if Gen.Utils.String_List.Has_Element (Iter) then Ada.Text_IO.Put_Line ("Dynamo project files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Gen.Utils.String_List.Next (Iter); end loop; end if; end Print_Dynamo_Projects; procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is begin Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project)); Print_Dynamo_Projects (Project); Print_Modules (Project, 1); declare Model_Dirs : Gen.Utils.String_List.Vector; begin Collect_Directories (List, Model_Dirs); declare Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First; begin Ada.Text_IO.Put_Line ("ADO model files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Util.Files.Iterate_Files_Path (Pattern => "*.xml", Path => Gen.Utils.String_List.Element (Iter), Process => Print_Model_File'Access); Gen.Utils.String_List.Next (Iter); end loop; end; end; end Print_Project; begin Generator.Read_Project ("dynamo.xml", True); Generator.Update_Project (Print_Project'Access); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); begin Ada.Text_IO.Put_Line ("info: Print information about the current project"); Ada.Text_IO.Put_Line ("Usage: info"); Ada.Text_IO.New_Line; end Help; end Gen.Commands.Info;
----------------------------------------------------------------------- -- gen-commands-info -- Collect and give information about the project -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Gen.Utils; with Gen.Utils.GNAT; with Gen.Model.Projects; with Util.Strings.Sets; with Util.Files; package body Gen.Commands.Info is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Args); procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector); procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean); procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition); procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition); procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count); procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition); procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector); List : Gen.Utils.String_List.Vector; Names : Util.Strings.Sets.Set; procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector) is procedure Add_Model_Dir (Base_Dir : in String; Dir : in String); procedure Add_Model_Dir (Base_Dir : in String; Dir : in String) is Path : constant String := Util.Files.Compose (Base_Dir, Dir); begin if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then Result.Append (Path); end if; end Add_Model_Dir; Iter : Gen.Utils.String_List.Cursor := List.First; begin while Gen.Utils.String_List.Has_Element (Iter) loop declare Path : constant String := Gen.Utils.String_List.Element (Iter); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Add_Model_Dir (Dir, "db"); Add_Model_Dir (Dir, "db/regtests"); Add_Model_Dir (Dir, "db/samples"); end; Gen.Utils.String_List.Next (Iter); end loop; end Collect_Directories; procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean) is pragma Unreferenced (Name); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (File); Done := False; end Print_Model_File; -- ------------------------------ -- Print the list of GNAT projects used by the main project. -- ------------------------------ procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is use Gen.Utils.GNAT; Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First; Info : Project_Info; begin if Project_Info_Vectors.Has_Element (Iter) then Ada.Text_IO.Put_Line ("GNAT project files:"); while Project_Info_Vectors.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Info := Project_Info_Vectors.Element (Iter); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path)); Project_Info_Vectors.Next (Iter); end loop; end if; end Print_GNAT_Projects; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := List.First; Ref : Model.Projects.Project_Reference; begin while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name)); Ada.Text_IO.Set_Col (Indent + 30); if Ref.Project /= null then Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path)); else Ada.Text_IO.Put_Line ("?"); end if; Project_Vectors.Next (Iter); end loop; end Print_Project_List; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := Project.Modules.First; Ref : Model.Projects.Project_Reference; begin if not Project.Modules.Is_Empty then Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put_Line ("Dynamo plugins:"); Print_Project_List (Indent, Project.Modules); Print_Project_List (Indent, Project.Dependencies); Iter := Project.Modules.First; while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then declare Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name); begin Ada.Text_IO.Set_Col (Indent); if Names.Contains (Name) then Ada.Text_IO.Put_Line ("!! " & Name); else Names.Insert (Name); Ada.Text_IO.Put_Line ("== " & Name); Print_Modules (Ref.Project.all, Indent + 4); Names.Delete (Name); end if; end; end if; Project_Vectors.Next (Iter); end loop; end if; end Print_Modules; -- ------------------------------ -- Print the list of Dynamo projects used by the main project. -- ------------------------------ procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First; begin if Gen.Utils.String_List.Has_Element (Iter) then Ada.Text_IO.Put_Line ("Dynamo project files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Gen.Utils.String_List.Next (Iter); end loop; end if; end Print_Dynamo_Projects; procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is begin Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project)); Print_Dynamo_Projects (Project); Print_Modules (Project, 1); declare Model_Dirs : Gen.Utils.String_List.Vector; begin Collect_Directories (List, Model_Dirs); declare Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First; begin Ada.Text_IO.Put_Line ("ADO model files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Util.Files.Iterate_Files_Path (Pattern => "*.xml", Path => Gen.Utils.String_List.Element (Iter), Process => Print_Model_File'Access); Gen.Utils.String_List.Next (Iter); end loop; end; end; end Print_Project; begin Generator.Read_Project ("dynamo.xml", True); Generator.Update_Project (Print_Project'Access); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); begin Ada.Text_IO.Put_Line ("info: Print information about the current project"); Ada.Text_IO.Put_Line ("Usage: info"); Ada.Text_IO.New_Line; end Help; end Gen.Commands.Info;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
c0ef346c121a8a99ec12f04f10b0bece4db3552f
matp/src/mat-expressions.adb
matp/src/mat-expressions.adb
----------------------------------------------------------------------- -- 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.Frames; 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); Resolver : Resolver_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; Region : MAT.Memory.Region_Info; begin if Resolver /= null then case Kind is when INSIDE_REGION | INSIDE_DIRECT_REGION => Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name)); when others => Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name)); end case; end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; 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_HAS_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 use type MAT.Types.Target_Tick_Ref; Result : Expression_Type; Start : MAT.Types.Target_Tick_Ref; begin if Resolver /= null then Start := Resolver.Get_Start_Time; else Start := 0; end if; if Max = MAT.Types.Target_Tick_Ref'Last then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min + Start, Max_Time => Max); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min + Start, Max_Time => Max + Start); end if; 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.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.Event_Id_Type; Max : in MAT.Events.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; -- ------------------------------ -- Create an expression node to keep allocation events which don't have any associated free. -- ------------------------------ function Create_No_Free return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NO_FREE); return Result; end Create_No_Free; -- ------------------------------ -- 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.Target_Event_Type) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Event); end if; 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; use type MAT.Types.Target_Thread_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 N_HAS_ADDR => return Addr <= Node.Min_Addr and Addr + Allocation.Size >= Node.Max_Addr; when N_IN_FUNC => return MAT.Frames.In_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_THREAD => return Allocation.Thread >= Node.Min_Thread and Allocation.Thread <= Node.Max_Thread; 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.Target_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.Event_Id_Type; use type MAT.Events.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 N_HAS_ADDR => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when N_IN_FUNC => return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String; Resolver : in Resolver_Type_Access) return Expression_Type is begin MAT.Expressions.Resolver := Resolver; 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.Frames; 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); Resolver : Resolver_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; Region : MAT.Memory.Region_Info; begin if Resolver /= null then case Kind is when INSIDE_REGION | INSIDE_DIRECT_REGION => Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name)); when others => Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name)); end case; end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; return Result; end Create_Inside; function Create_Inside (Addr : in Mat.Types.Uint64; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; Region : MAT.Memory.Region_Info; begin if Resolver /= null then Region := Resolver.Find_Symbol (Addr); end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; 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_HAS_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 use type MAT.Types.Target_Tick_Ref; Result : Expression_Type; Start : MAT.Types.Target_Tick_Ref; begin if Resolver /= null then Start := Resolver.Get_Start_Time; else Start := 0; end if; if Max = MAT.Types.Target_Tick_Ref'Last then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min + Start, Max_Time => Max); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min + Start, Max_Time => Max + Start); end if; 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.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.Event_Id_Type; Max : in MAT.Events.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; -- ------------------------------ -- Create an expression node to keep allocation events which don't have any associated free. -- ------------------------------ function Create_No_Free return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NO_FREE); return Result; end Create_No_Free; -- ------------------------------ -- 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.Target_Event_Type) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Event); end if; 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; use type MAT.Types.Target_Thread_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 N_HAS_ADDR => return Addr <= Node.Min_Addr and Addr + Allocation.Size >= Node.Max_Addr; when N_IN_FUNC => return MAT.Frames.In_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_THREAD => return Allocation.Thread >= Node.Min_Thread and Allocation.Thread <= Node.Max_Thread; 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.Target_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.Event_Id_Type; use type MAT.Events.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 N_HAS_ADDR => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when N_IN_FUNC => return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String; Resolver : in Resolver_Type_Access) return Expression_Type is begin MAT.Expressions.Resolver := Resolver; 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;
Implement new Create_Inside function
Implement new Create_Inside function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
350b5215196ef70858f414611f431588074646d7
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
Letractively/ada-security
330a86acbed85c612bc837d00a69cf22d9c9a08f
src/ado-c.adb
src/ado-c.adb
----------------------------------------------------------------------- -- ado-c -- Support for driver implementation -- 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. ----------------------------------------------------------------------- package body ADO.C is use Ada.Strings.Unbounded; use type Interfaces.C.Strings.chars_ptr; -- ------------------------------ -- Convert a string to a C string. -- ------------------------------ function To_String_Ptr (S : String) return String_Ptr is begin return Result : String_Ptr do Result.Ptr := Strings.New_String (S); end return; end To_String_Ptr; -- ------------------------------ -- Convert an unbounded string to a C string. -- ------------------------------ function To_String_Ptr (S : Ada.Strings.Unbounded.Unbounded_String) return String_Ptr is begin return Result : String_Ptr do Result.Ptr := Strings.New_String (To_String (S)); end return; end To_String_Ptr; -- ------------------------------ -- Get the C string pointer. -- ------------------------------ function To_C (S : String_Ptr) return Interfaces.C.Strings.chars_ptr is begin return S.Ptr; end To_C; -- ------------------------------ -- Set the string -- ------------------------------ procedure Set_String (S : in out String_Ptr; Value : in String) is begin if S.Ptr /= Interfaces.C.Strings.Null_Ptr then Strings.Free (S.Ptr); end if; S.Ptr := Strings.New_String (Value); end Set_String; -- ------------------------------ -- Reclaim the storage held by the C string. -- ------------------------------ procedure Finalize (S : in out String_Ptr) is begin Strings.Free (S.Ptr); end Finalize; end ADO.C;
----------------------------------------------------------------------- -- ado-c -- Support for driver implementation -- Copyright (C) 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.C is use Ada.Strings.Unbounded; use type Interfaces.C.Strings.chars_ptr; -- ------------------------------ -- Convert a string to a C string. -- ------------------------------ function To_String_Ptr (S : String) return String_Ptr is begin return Result : String_Ptr do Result.Ptr := Strings.New_String (S); end return; end To_String_Ptr; -- ------------------------------ -- Get the C string pointer. -- ------------------------------ function To_C (S : String_Ptr) return Interfaces.C.Strings.chars_ptr is begin return S.Ptr; end To_C; -- ------------------------------ -- Set the string -- ------------------------------ procedure Set_String (S : in out String_Ptr; Value : in String) is begin if S.Ptr /= Interfaces.C.Strings.Null_Ptr then Strings.Free (S.Ptr); end if; S.Ptr := Strings.New_String (Value); end Set_String; -- ------------------------------ -- Reclaim the storage held by the C string. -- ------------------------------ procedure Finalize (S : in out String_Ptr) is begin Strings.Free (S.Ptr); end Finalize; end ADO.C;
Remove unused To_String_Ptr operation
Remove unused To_String_Ptr operation
Ada
apache-2.0
stcarrez/ada-ado
05009f69a965b685f371693584a81f77c0c4d402
awa/plugins/awa-storages/regtests/awa-storages-tests.ads
awa/plugins/awa-storages/regtests/awa-storages-tests.ads
----------------------------------------------------------------------- -- awa-storages-tests -- Unit tests for storages module -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with Servlet.requests.Mockup; with Servlet.Responses.Mockup; with Ada.Strings.Unbounded; package AWA.Storages.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Folder_Ident : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the wiki page as anonymous users. procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String); -- Verify that the wiki lists contain the given page. procedure Verify_List_Contains (T : in out Test; Page : in String); -- Test access to the wiki as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of document by simulating web requests. procedure Test_Create_Document (T : in out Test); -- Test getting a document which does not exist. procedure Test_Missing_Document (T : in out Test); end AWA.Storages.Tests;
----------------------------------------------------------------------- -- awa-storages-tests -- Unit tests for storages module -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; package AWA.Storages.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Folder_Ident : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the wiki page as anonymous users. procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String); -- Verify that the wiki lists contain the given page. procedure Verify_List_Contains (T : in out Test; Page : in String); -- Test access to the wiki as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of document by simulating web requests. procedure Test_Create_Document (T : in out Test); -- Test getting a document which does not exist. procedure Test_Missing_Document (T : in out Test); end AWA.Storages.Tests;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9768c0502ca4b5f0d15977c318b83f47636f4ec0
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- 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.Exceptions; with AUnit; with AUnit.Test_Caller; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with Regtests; with Regtests.Simple.Model; with Util.Measures; with Util.Log; with Util.Log.Loggers; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new AUnit.Test_Caller (Test); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then Assert (T, Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Suite.Add_Test (Caller.Create ("Test Object_Ref.Load", Test_Load'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Save", Test_Create_Load'Access)); Suite.Add_Test (Caller.Create ("Test Master_Connection init error", Test_Not_Open'Access)); Suite.Add_Test (Caller.Create ("Test Sequences.Factory", Test_Allocate'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Save/Create/Update", Test_Create_Save'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access)); Suite.Add_Test (Caller.Create ("Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access)); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- 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.Exceptions; with AUnit; with AUnit.Test_Caller; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with Regtests; with Regtests.Simple.Model; with Util.Measures; with Util.Log; with Util.Log.Loggers; package body ADO.Tests is use Util.Log; use Ada.Exceptions; use ADO.Statements; use type Regtests.Simple.Model.User_Ref; use type Regtests.Simple.Model.Allocate_Ref; Log : constant Loggers.Logger := Loggers.Create ("ADO.Tests"); package Caller is new AUnit.Test_Caller (Test); procedure Fail (T : in Test; Message : in String); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); procedure Fail (T : in Test; Message : in String) is begin T.Assert (False, Message); end Fail; procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence) is Message : constant String := Exception_Message (E); begin Log.Info ("Exception: {0}", Message); T.Assert (Message'Length > 0, "Exception " & Exception_Name (E) & " does not have any message"); end Assert_Has_Message; procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Is_Null -- ------------------------------ procedure Test_Load (T : in out Test) is DB : ADO.Sessions.Session := Regtests.Get_Database; Object : Regtests.Simple.Model.User_Ref; begin T.Assert (Object.Is_Null, "Object_Ref.Is_Null: Empty object must be null"); Object.Load (DB, -1); T.Assert (False, "Object_Ref.Load: Load must raise NOT_FOUND exception"); exception when ADO.Objects.NOT_FOUND => T.Assert (Object.Is_Null, "Object_Ref.Load: Must not change the object"); end Test_Load; -- ------------------------------ -- Check: -- Object_Ref.Load -- Object_Ref.Save -- <Model>.Set_xxx (Unbounded_String) -- <Model>.Create -- ------------------------------ procedure Test_Create_Load (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Object : Regtests.Simple.Model.User_Ref; Check : Regtests.Simple.Model.User_Ref; begin -- Initialize and save an object Object.Set_Name ("A simple test name"); Object.Save (DB); T.Assert (Object.Get_Id > 0, "Saving an object did not allocate an identifier"); -- Load the object Check.Load (DB, Object.Get_Id); T.Assert (not Check.Is_Null, "Object_Ref.Load: Loading the object failed"); end Test_Create_Load; -- ------------------------------ -- Check: -- Various error checks on database connections -- -- Master_Connection.Rollback -- ------------------------------ procedure Test_Not_Open (T : in out Test) is DB : ADO.Sessions.Master_Session; begin begin DB.Rollback; Fail (T, "Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; begin DB.Commit; Fail (T, "Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.NOT_OPEN => Assert_Has_Message (T, E); end; end Test_Not_Open; -- ------------------------------ -- Check id generation -- ------------------------------ procedure Test_Allocate (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Key : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access); PrevId : Identifier := NO_IDENTIFIER; S : Util.Measures.Stamp; begin for I in 1 .. 200 loop declare Obj : Regtests.Simple.Model.Allocate_Ref; begin Obj.Save (DB); Key := Obj.Get_Key; if PrevId /= NO_IDENTIFIER then T.Assert (Objects.Get_Value (Key) = PrevId + 1, "Invalid allocated identifier: " & Objects.To_String (Key) & " previous=" & Identifier'Image (PrevId)); end if; PrevId := Objects.Get_Value (Key); end; end loop; Util.Measures.Report (S, "Allocate 200 ids"); end Test_Allocate; -- ------------------------------ -- Check: -- Object.Save (with creation) -- Object.Find -- Object.Save (update) -- ------------------------------ procedure Test_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); Ref.Set_Name ("Testing the allocation: update"); Ref.Save (DB); Ref2.Load (DB, Ref.Get_Id); end Test_Create_Save; -- ------------------------------ -- Check: -- Object.Save (with creation) -- ------------------------------ procedure Test_Perf_Create_Save (T : in out Test) is use ADO.Objects; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; S : Util.Measures.Stamp; begin DB.Begin_Transaction; for I in 1 .. 1_000 loop declare Ref : Regtests.Simple.Model.Allocate_Ref; begin Ref.Set_Name ("Testing the allocation"); Ref.Save (DB); T.Assert (Ref.Get_Id > 0, "Object must have an id"); end; end loop; DB.Commit; Util.Measures.Report (S, "Create 1000 rows"); end Test_Perf_Create_Save; procedure Test_Delete_All (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE'Access); Result : Natural; begin DB.Begin_Transaction; Stmt.Execute (Result); Log.Info ("Deleted {0} rows", Natural'Image (Result)); DB.Commit; T.Assert (Result > 100, "Too few rows were deleted"); end Test_Delete_All; procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Suite.Add_Test (Caller.Create ("Test Object_Ref.Load", Test_Load'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Save", Test_Create_Load'Access)); Suite.Add_Test (Caller.Create ("Test Master_Connection init error", Test_Not_Open'Access)); Suite.Add_Test (Caller.Create ("Test Sequences.Factory", Test_Allocate'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Save/Create/Update", Test_Create_Save'Access)); Suite.Add_Test (Caller.Create ("Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access)); Suite.Add_Test (Caller.Create ("Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access)); end Add_Tests; end ADO.Tests;
Fix compilation with GNAT 2011
Fix compilation with GNAT 2011
Ada
apache-2.0
stcarrez/ada-ado
62e5651227f4751a7670a53013579ad3cbafd105
resources/scripts/api/spyse.ads
resources/scripts/api/spyse.ads
-- Copyright 2017-2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. local json = require("json") name = "Spyse" type = "api" function start() setratelimit(1) end function check() local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c ~= nil and c.key ~= nil and c.key ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end for i = 0,10000,100 do local u = subsurl(domain, i) local resp = getpage(ctx, u, c.key, cfg.ttl) if (resp == "") then break end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return false end for i, item in pairs(d['data'].items) do sendnames(ctx, item.name) end end end function subsurl(domain, offset) return "https://api.spyse.com/v3/data/domain/subdomain?domain=" .. domain .. "&limit=100&offset=" .. tostring(offset) end function horizontal(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end -- Spyse API domain/related/domain often returns false positives (domains not owned by the provided domain) --horizonnames(ctx, domain, c.key, cfg.ttl) horizoncerts(ctx, domain, c.key, cfg.ttl) end function horizonnames(ctx, domain, key, ttl) for i = 0,10000,100 do u = namesurl(domain, i) resp = getpage(ctx, u, key, ttl) if (resp == "") then break end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then break end for i, item in pairs(d['data'].items) do if (item.domain.name ~= "") then local names = find(item.domain.name, subdomainre) if (names ~= nil and #names > 0 and names[1] ~= "") then associated(ctx, domain, names[1]) end end end end end function namesurl(domain, offset) return "https://api.spyse.com/v3/data/domain/related/domain?domain=" .. domain .. "&limit=100&offset=" .. tostring(offset) end function horizoncerts(ctx, domain, key, ttl) local u = "https://api.spyse.com/v3/data/domain/org?domain=" .. domain local resp = getpage(ctx, u, key, ttl) if (resp == "") then return end local d = json.decode(resp) if (d == nil or d['data'].id == nil) then return end local orgid = d['data'].id for i = 0,10000,100 do u = certsurl(orgid, i) resp = getpage(ctx, u, key, ttl) if (resp == "") then break end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then break end for i, item in pairs(d['data'].items) do local san = item.parsed.extensions.subject_alt_name if (san ~= nil and #(san.dns_names) > 0) then for j, name in pairs(san.dns_names) do local names = find(name, subdomainre) if (names ~= nil and #names > 0 and names[1] ~= "") then associated(ctx, domain, names[1]) end end end end end end function certsurl(id, offset) return "https://api.spyse.com/v3/data/org/cert/subject?id=" .. id .. "&limit=100&offset=" .. tostring(offset) end function asn(ctx, addr, asn) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local prefix if (asn == 0) then if (addr == "") then return end asn, prefix = getasn(ctx, addr, c.key, cfg.ttl) if (asn == 0) then return end end local a = asinfo(ctx, asn, c.key, cfg.ttl) if (a == nil or #(a.netblocks) == 0) then return end if (prefix == "") then prefix = a.netblocks[1] parts = split(prefix, "/") addr = parts[1] end newasn(ctx, { ['addr']=addr, ['asn']=asn, ['prefix']=prefix, ['desc']=a.desc, ['netblocks']=a.netblocks, }) end function getasn(ctx, ip, key, ttl) local u = "https://api.spyse.com/v3/data/ip?ip=" .. tostring(ip) local resp = getpage(ctx, u, key, ttl) if (resp == "") then return 0, "" end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return 0, "" end local cidr local asn = 0 for i, item in pairs(d['data'].items) do local num = item.isp_info.as_num if (asn == 0 or asn < num) then asn = num cidr = item.cidr end end return asn, cidr end function asinfo(ctx, asn, key, ttl) local u = "https://api.spyse.com/v3/data/as?asn=" .. tostring(asn) local resp = getpage(ctx, u, key, ttl) if (resp == "") then return nil end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return nil end local cidrs = {} for i, p in pairs(d.items[1].ipv4_cidr_array) do table.insert(cidrs, p.ip .. "/" .. tostring(p.cidr)) end for i, p in pairs(d.items[1].ipv6_cidr_array) do table.insert(cidrs, p.ip .. "/" .. tostring(p.cidr)) end return { desc=d.items[1].as_org, netblocks=cidrs, } end function getpage(ctx, url, key, ttl) local resp, err = request(ctx, { ['url']=url, headers={ ['Authorization']="Bearer " .. key, ['Content-Type']="application/json", }, }) if (err ~= nil and err ~= "") then return "" end return resp end function sendnames(ctx, content) local names = find(content, subdomainre) if (names == nil) then return end local found = {} for i, v in pairs(names) do if (found[v] == nil) then newname(ctx, v) found[v] = true end end end function split(str, delim) local result = {} local pattern = "[^%" .. delim .. "]+" local matches = find(str, pattern) if (matches == nil or #matches == 0) then return result end for i, match in pairs(matches) do table.insert(result, match) end return result end
-- Copyright 2017-2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. local json = require("json") name = "Spyse" type = "api" function start() setratelimit(1) end function check() local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c ~= nil and c.key ~= nil and c.key ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local step = 100 for i = 0,10000,step do local payload = '{"search_params":[{"name":{"operator":"ends","value":".' .. domain .. '"}}],"limit":100,"offset":' .. tostring(i) .. '}' local resp = postreq(ctx, "https://api.spyse.com/v4/data/domain/search", c.key, cfg.ttl, payload) if (resp == "") then break end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return false end for i, item in pairs(d['data'].items) do sendnames(ctx, item.name) end if (i+step >= d['data'].total_items) then break end end end function horizontal(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end horizoncerts(ctx, domain, c.key, cfg.ttl) end function horizoncerts(ctx, domain, key, ttl) local u = "https://api.spyse.com/v4/data/domain/" .. domain local resp = getpage(ctx, u, key, ttl) if (resp == "") then return end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return end if (d['data'].items[0].cert_summary == nil) then return end local certid = d['data'].items[0].cert_summary.fingerprint_sha256 u = "https://api.spyse.com/v4/data/certificate/" .. certid resp = getpage(ctx, u, key, ttl) if (resp == "") then return end d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return end local san = d['data'].items[0].parsed.extensions.subject_alt_name if (san ~= nil and #(san.dns_names) > 0) then for j, name in pairs(san.dns_names) do local names = find(name, subdomainre) if (names ~= nil and #names > 0 and names[1] ~= "") then associated(ctx, domain, names[1]) end end end end function asn(ctx, addr, asn) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local prefix if (asn == 0) then if (addr == "") then return end asn, prefix = getasn(ctx, addr, c.key, cfg.ttl) if (asn == 0) then return end end local a = asinfo(ctx, asn, c.key, cfg.ttl) if (a == nil or #(a.netblocks) == 0) then return end if (prefix == "") then prefix = a.netblocks[1] parts = split(prefix, "/") addr = parts[1] end newasn(ctx, { ['addr']=addr, ['asn']=asn, ['prefix']=prefix, ['desc']=a.desc, ['netblocks']=a.netblocks, }) end function getasn(ctx, ip, key, ttl) local u = "https://api.spyse.com/v4/data/ip/" .. tostring(ip) local resp = getpage(ctx, u, key, ttl) if (resp == "") then return 0, "" end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return 0, "" end local cidr local asn = 0 for i, item in pairs(d['data'].items) do local num = item.isp_info.as_num if (asn == 0 or asn < num) then asn = num cidr = item.cidr end end return asn, cidr end function asinfo(ctx, asn, key, ttl) local u = "https://api.spyse.com/v4/data/as/" .. tostring(asn) local resp = getpage(ctx, u, key, ttl) if (resp == "") then return nil end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return nil end local cidrs = {} for i, p in pairs(d.items[1].ipv4_cidr_array) do table.insert(cidrs, p.ip .. "/" .. tostring(p.cidr)) end for i, p in pairs(d.items[1].ipv6_cidr_array) do table.insert(cidrs, p.ip .. "/" .. tostring(p.cidr)) end return { desc=d.items[1].as_org, netblocks=cidrs, } end function getpage(ctx, url, key, ttl) local resp, err = request(ctx, { ['url']=url, headers={ ['Authorization']="Bearer " .. key, ['Content-Type']="application/json", }, }) if (err ~= nil and err ~= "") then return "" end return resp end function postreq(ctx, url, key, ttl, payload) local resp, err = request(ctx, { ['url']=url, method="POST", data=payload, headers={ ['Authorization']="Bearer " .. key, ['Content-Type']="application/json", }, }) if (err ~= nil and err ~= "") then return "" end return resp end function sendnames(ctx, content) local names = find(content, subdomainre) if (names == nil) then return end local found = {} for i, v in pairs(names) do if (found[v] == nil) then newname(ctx, v) found[v] = true end end end function split(str, delim) local result = {} local pattern = "[^%" .. delim .. "]+" local matches = find(str, pattern) if (matches == nil or #matches == 0) then return result end for i, match in pairs(matches) do table.insert(result, match) end return result end
update spyse api script
improvement: update spyse api script
Ada
apache-2.0
caffix/amass,caffix/amass
f2d1f5b5786776d5cb38974a0bf57ff4ab11b279
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, To_String (Util.Locales.ENGLISH), 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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;
Update and add some locale test
Update and add some locale test
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
3f96b7029cda93b49bbf1aa72d43e156aa9c8dcf
src/aws/asf-requests-web.adb
src/aws/asf-requests-web.adb
----------------------------------------------------------------------- -- asf.requests -- ASF Requests -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Attachments.Extend; with AWS.Containers.Tables; with AWS.Parameters; with Util.Strings; with ASF.Parts.Web; package body ASF.Requests.Web is function Get_Parameter (R : Request; Name : String) return String is begin return AWS.Status.Parameter (R.Data.all, Name); end Get_Parameter; -- ------------------------------ -- Iterate over the request parameters and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Parameters (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Name, Value : in String); procedure Process_Wrapper (Name, Value : in String) is Last : Natural := Value'First; Pos : Natural; begin while Last <= Value'Last loop Pos := Util.Strings.Index (Value, ASCII.NUL, Last); if Pos > 0 then Process (Name, Value (Last .. Pos - 1)); Last := Pos + 1; else Process (Name, Value (Last .. Value'Last)); return; end if; end loop; end Process_Wrapper; P : constant AWS.Parameters.List := AWS.Status.Parameters (Req.Data.all); begin AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (P), "" & ASCII.NUL, Process_Wrapper'Access); end Iterate_Parameters; -- ------------------------------ -- Set the AWS data received to initialize the request object. -- ------------------------------ procedure Set_Request (Req : in out Request; Data : access AWS.Status.Data) is begin Req.Data := Data; Req.Headers := AWS.Status.Header (Data.all); end Set_Request; -- ------------------------------ -- Returns the name of the HTTP method with which this request was made, -- for example, GET, POST, or PUT. Same as the value of the CGI variable -- REQUEST_METHOD. -- ------------------------------ function Get_Method (Req : in Request) return String is begin return AWS.Status.Method (Req.Data.all); end Get_Method; -- ------------------------------ -- Returns the name and version of the protocol the request uses in the form -- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets, -- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL. -- ------------------------------ function Get_Protocol (Req : in Request) return String is begin return AWS.Status.HTTP_Version (Req.Data.all); end Get_Protocol; -- ------------------------------ -- Returns the part of this request's URL from the protocol name up to the query -- string in the first line of the HTTP request. The web container does not decode -- this String. For example: -- First line of HTTP request Returned Value -- POST /some/path.html HTTP/1.1 /some/path.html -- GET http://foo.bar/a.html HTTP/1.0 /a.html -- HEAD /xyz?a=b HTTP/1.1 /xyz -- ------------------------------ function Get_Request_URI (Req : in Request) return String is begin return AWS.Status.URI (Req.Data.all); end Get_Request_URI; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any request header. -- ------------------------------ function Get_Header (Req : in Request; Name : in String) return String is Values : constant AWS.Headers.VString_Array := AWS.Headers.Get_Values (Req.Headers, Name); begin if Values'Length > 0 then return To_String (Values (Values'First)); else return ""; end if; end Get_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is begin Req.Headers.Iterate_Names (", ", Process => Process); end Iterate_Headers; -- ------------------------------ -- Returns all the values of the specified request header as an Enumeration -- of String objects. -- -- Some headers, such as Accept-Language can be sent by clients as several headers -- each with a different value rather than sending the header as a comma -- separated list. -- -- If the request did not include any headers of the specified name, this method -- returns an empty Enumeration. The header name is case insensitive. You can use -- this method with any request header. -- ------------------------------ function Get_Headers (Req : in Request; Name : in String) return String is begin return AWS.Headers.Get_Values (Req.Headers, Name); end Get_Headers; -- ------------------------------ -- Returns the Internet Protocol (IP) address of the client or last proxy that -- sent the request. For HTTP servlets, same as the value of the CGI variable -- REMOTE_ADDR. -- ------------------------------ function Get_Remote_Addr (Req : in Request) return String is begin return AWS.Status.Peername (Req.Data.all); end Get_Remote_Addr; -- ------------------------------ -- Get the number of parts included in the request. -- ------------------------------ function Get_Part_Count (Req : in Request) return Natural is begin return AWS.Attachments.Count (AWS.Status.Attachments (Req.Data.all)); end Get_Part_Count; -- ------------------------------ -- Process the part at the given position and executes the <b>Process</b> operation -- with the part object. -- ------------------------------ procedure Process_Part (Req : in out Request; Position : in Positive; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all); begin ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Position), Process); end Process_Part; -- ------------------------------ -- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation -- with the part object. -- ------------------------------ procedure Process_Part (Req : in out Request; Id : in String; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is procedure Process_Part (E : in AWS.Attachments.Element); procedure Process_Part (E : in AWS.Attachments.Element) is Name : constant String := AWS.Attachments.Extend.Get_Name (E); begin if Id = Name then ASF.Parts.Web.Process_Part (E, Process); end if; end Process_Part; Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all); begin AWS.Attachments.Iterate (Attachs, Process_Part'Access); -- ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Id), Process); end Process_Part; end ASF.Requests.Web;
----------------------------------------------------------------------- -- asf.requests -- ASF Requests -- 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 AWS.Attachments.Extend; with AWS.Containers.Tables; with AWS.Parameters; with Util.Strings; with ASF.Parts.Web; package body ASF.Requests.Web is function Get_Parameter (R : Request; Name : String) return String is begin return AWS.Status.Parameter (R.Data.all, Name); end Get_Parameter; -- ------------------------------ -- Iterate over the request parameters and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Parameters (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Name, Value : in String); procedure Process_Wrapper (Name, Value : in String) is Last : Natural := Value'First; Pos : Natural; begin while Last <= Value'Last loop Pos := Util.Strings.Index (Value, ASCII.NUL, Last); if Pos > 0 then Process (Name, Value (Last .. Pos - 1)); Last := Pos + 1; else Process (Name, Value (Last .. Value'Last)); return; end if; end loop; end Process_Wrapper; P : constant AWS.Parameters.List := AWS.Status.Parameters (Req.Data.all); begin AWS.Containers.Tables.Iterate_Names (AWS.Containers.Tables.Table_Type (P), "" & ASCII.NUL, Process_Wrapper'Access); end Iterate_Parameters; -- ------------------------------ -- Set the AWS data received to initialize the request object. -- ------------------------------ procedure Set_Request (Req : in out Request; Data : access AWS.Status.Data) is begin Req.Data := Data; Req.Headers := AWS.Status.Header (Data.all); end Set_Request; -- ------------------------------ -- Returns the name of the HTTP method with which this request was made, -- for example, GET, POST, or PUT. Same as the value of the CGI variable -- REQUEST_METHOD. -- ------------------------------ function Get_Method (Req : in Request) return String is begin return AWS.Status.Method (Req.Data.all); end Get_Method; -- ------------------------------ -- Returns the name and version of the protocol the request uses in the form -- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets, -- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL. -- ------------------------------ function Get_Protocol (Req : in Request) return String is begin return AWS.Status.HTTP_Version (Req.Data.all); end Get_Protocol; -- ------------------------------ -- Returns the part of this request's URL from the protocol name up to the query -- string in the first line of the HTTP request. The web container does not decode -- this String. For example: -- First line of HTTP request Returned Value -- POST /some/path.html HTTP/1.1 /some/path.html -- GET http://foo.bar/a.html HTTP/1.0 /a.html -- HEAD /xyz?a=b HTTP/1.1 /xyz -- ------------------------------ function Get_Request_URI (Req : in Request) return String is begin return AWS.Status.URI (Req.Data.all); end Get_Request_URI; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any request header. -- ------------------------------ function Get_Header (Req : in Request; Name : in String) return String is Values : constant AWS.Headers.VString_Array := AWS.Headers.Get_Values (Req.Headers, Name); begin if Values'Length > 0 then return To_String (Values (Values'First)); else return ""; end if; end Get_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Req : in Request; Process : not null access procedure (Name : in String; Value : in String)) is begin Req.Headers.Iterate_Names (", ", Process => Process); end Iterate_Headers; -- ------------------------------ -- Returns all the values of the specified request header as an Enumeration -- of String objects. -- -- Some headers, such as Accept-Language can be sent by clients as several headers -- each with a different value rather than sending the header as a comma -- separated list. -- -- If the request did not include any headers of the specified name, this method -- returns an empty Enumeration. The header name is case insensitive. You can use -- this method with any request header. -- ------------------------------ function Get_Headers (Req : in Request; Name : in String) return String is begin return AWS.Headers.Get_Values (Req.Headers, Name); end Get_Headers; -- ------------------------------ -- Returns the Internet Protocol (IP) address of the client or last proxy that -- sent the request. For HTTP servlets, same as the value of the CGI variable -- REMOTE_ADDR. -- ------------------------------ function Get_Remote_Addr (Req : in Request) return String is begin return AWS.Status.Peername (Req.Data.all); end Get_Remote_Addr; -- ------------------------------ -- Get the number of parts included in the request. -- ------------------------------ function Get_Part_Count (Req : in Request) return Natural is begin return AWS.Attachments.Count (AWS.Status.Attachments (Req.Data.all)); end Get_Part_Count; -- ------------------------------ -- Process the part at the given position and executes the <b>Process</b> operation -- with the part object. -- ------------------------------ procedure Process_Part (Req : in out Request; Position : in Positive; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all); begin ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Position), Process); end Process_Part; -- ------------------------------ -- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation -- with the part object. -- ------------------------------ procedure Process_Part (Req : in out Request; Id : in String; Process : not null access procedure (Data : in ASF.Parts.Part'Class)) is procedure Process_Part (E : in AWS.Attachments.Element); procedure Process_Part (E : in AWS.Attachments.Element) is Name : constant String := AWS.Attachments.Extend.Get_Name (E); begin if Id = Name then ASF.Parts.Web.Process_Part (E, Process); end if; end Process_Part; Attachs : constant AWS.Attachments.List := AWS.Status.Attachments (Req.Data.all); begin AWS.Attachments.Iterate (Attachs, Process_Part'Access); -- ASF.Parts.Web.Process_Part (AWS.Attachments.Get (Attachs, Id), Process); end Process_Part; -- ------------------------------ -- 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 Request; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is begin AWS.Status.Read_Body (D => Stream.Data.all, Buffer => Into, Last => Last); end Read; overriding function Create_Input_Stream (Req : in Request) return ASF.Streams.Input_Stream_Access is Result : constant ASF.Streams.Input_Stream_Access := new ASF.Streams.Input_Stream; begin Result.Initialize (Output => null, Input => Req'Unrestricted_Access, Size => 8192); return Result; end Create_Input_Stream; end ASF.Requests.Web;
Implement the Read and Create_Input_Stream operations
Implement the Read and Create_Input_Stream operations
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
91c6cfb01945c824da33c350f0351688f02c8559
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 ADO.Sessions.Entities; with AWA.Services.Contexts; 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 pragma Unreferenced (Outcome); 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 pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Answer (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module.Get_Question_Manager; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; 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 pragma Unreferenced (Outcome); 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 pragma Unreferenced (Outcome); begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "question_id" then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Question.Get_Id)); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Answer (From, From.Question, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the answer bean instance. -- ------------------------------ function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Answer_Bean_Access := new Answer_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Answer_Bean; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "answers" then return Util.Beans.Objects.To_Object (Value => From.Answer_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "question" then return Util.Beans.Objects.To_Object (Value => From.Question_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare package ASC renames AWA.Services.Contexts; use AWA.Questions.Models; use AWA.Services; Session : ADO.Sessions.Session := From.Service.Get_Session; Query : ADO.Queries.Context; List : AWA.Questions.Models.Question_Display_Info_List_Bean; Ctx : constant ASC.Service_Context_Access := ASC.Current; begin Query.Set_Query (AWA.Questions.Models.Query_Question_Info); Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.QUESTION_TABLE, Session => Session); AWA.Questions.Models.List (List, Session, Query); if not List.List.Is_Empty then From.Question := List.List.Element (0); end if; Query.Clear; Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value)); Query.Bind_Param ("user_id", Ctx.Get_User_Identifier); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "entity_type", Table => AWA.Questions.Models.ANSWER_TABLE, Session => Session); Query.Set_Query (AWA.Questions.Models.Query_Answer_List); AWA.Questions.Models.List (From.Answer_List, Session, Query); end; end if; end Set_Value; -- ------------------------------ -- Create the Question_Display_Bean bean instance. -- ------------------------------ function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Display_Bean_Access := new Question_Display_Bean; begin Object.Service := Module.Get_Question_Manager; Object.Question_Bean := Object.Question'Access; Object.Answer_List_Bean := Object.Answer_List'Access; return Object.all'Access; end Create_Question_Display_Bean; end AWA.Questions.Beans;
Load the question associated with the answer
Load the question associated with the answer
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
b39de359accbe4948d6aff07b083bc81cabbcbc6
awa/src/awa-components-wikis.adb
awa/src/awa-components-wikis.adb
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Documents; with Wiki.Parsers; with Wiki.Helpers; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Filters.Autolink; with Wiki.Streams.Html; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then return Wiki.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.SYNTAX_CREOLE; elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; else return Wiki.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Get the links renderer that must be used to render image and page links. -- ------------------------------ function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Get the plugin factory that must be used by the Wiki parser. -- ------------------------------ function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, PLUGINS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Wiki.Plugins.Plugin_Factory'Class) then return null; else return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access; end if; end Get_Plugin_Factory; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Links.Link_Renderer_Access; use type Wiki.Plugins.Plugin_Factory_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Plugins := UI.Get_Plugin_Factory (Context); if Plugins /= null then Engine.Set_Plugin_Factory (Plugins); end if; Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_String (Value), Doc); Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Set_Render_TOC (UI.Get_Attribute (TOC_NAME, Context, False)); Renderer.Render (Doc); end if; Writer.End_Element ("div"); end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is begin if Wiki.Helpers.Is_Url (Link) then URI := To_Unbounded_Wide_Wide_String (Link); else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Documents; with Wiki.Parsers; with Wiki.Helpers; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Filters.Autolink; with Wiki.Streams.Html; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then return Wiki.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.SYNTAX_CREOLE; elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; else return Wiki.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Get the links renderer that must be used to render image and page links. -- ------------------------------ function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Get the plugin factory that must be used by the Wiki parser. -- ------------------------------ function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, PLUGINS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Wiki.Plugins.Plugin_Factory'Class) then return null; else return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access; end if; end Get_Plugin_Factory; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Links.Link_Renderer_Access; use type Wiki.Plugins.Plugin_Factory_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Plugins := UI.Get_Plugin_Factory (Context); if Plugins /= null then Engine.Set_Plugin_Factory (Plugins); end if; Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_String (Value), Doc); Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Set_Render_TOC (UI.Get_Attribute (TOC_NAME, Context, False)); Renderer.Render (Doc); end if; Writer.End_Element ("div"); end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is begin if Wiki.Helpers.Is_Url (Link) then URI := To_Unbounded_Wide_Wide_String (Link); else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in out Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
Change Make_Image_Link procedure to use in out parameter for Width and Height
Change Make_Image_Link procedure to use in out parameter for Width and Height
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
43a89e4f7878f612eb20d352cce8a6fd3abb4491
src/gl/implementation/gl-enums-internalformat.ads
src/gl/implementation/gl-enums-internalformat.ads
-- Copyright (c) 2018 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. package GL.Enums.Internalformat is pragma Preelaborate; type Parameter is (Samples, Internalformat_Supported, Internalformat_Preferred, Internalformat_Red_Size, Internalformat_Green_Size, Internalformat_Blue_Size, Internalformat_Alpha_Size, Internalformat_Depth_Size, Internalformat_Stencil_Size, Internalformat_Shared_Size, Internalformat_Red_Type, Internalformat_Green_Type, Internalformat_Blue_Type, Internalformat_Alpha_Type, Internalformat_Depth_Type, Internalformat_Stencil_Type, Max_Width, Max_Height, Max_Depth, Max_Layers, Max_Combined_Dimensions, Color_Components, Depth_Components, Stencil_Components, Color_Renderable, Depth_Renderable, Stencil_Renderable, Framebuffer_Renderable, Framebuffer_Renderable_Layered, Framebuffer_Blend, Read_Pixels, Read_Pixels_Format, Read_Pixels_Type, Texture_Image_Format, Texture_Image_Type, Get_Texture_Image_Format, Get_Texture_Image_Type, Mipmap, Manual_Generate_Mipmap, Auto_Generate_Mipmap, Color_Encoding, sRGB_Read, sRGB_Write, sRGB_Decode_ARB, Filter, Vertex_Texture, Tess_Control_Texture, Tess_Evaluation_Texture, Geometry_Texture, Fragment_Texture, Compute_Texture, Texture_Shadow, Texture_Gather, Texture_Gather_Shadow, Shader_Image_Load, Shader_Image_Store, Shader_Image_Atomic, Image_Texel_Size, Image_Compatibility_Class, Image_Pixel_Format, Image_Pixel_Type, Simultaneous_Texture_And_Depth_Test, Simultaneous_Texture_And_Stencil_Test, Simultaneous_Texture_And_Depth_Write, Simultaneous_Texture_And_Stencil_Write, Texture_Compressed_Block_Width, Texture_Compressed_Block_Height, Texture_Compressed_Block_Size, Clear_Buffer, Texture_View, View_Compatibility_Class, Texture_Compressed, Image_Format_Compatibility_Type, Num_Sample_Counts); private for Parameter use (Samples => 16#80A9#, Internalformat_Supported => 16#826F#, Internalformat_Preferred => 16#8270#, Internalformat_Red_Size => 16#8271#, Internalformat_Green_Size => 16#8272#, Internalformat_Blue_Size => 16#8273#, Internalformat_Alpha_Size => 16#8274#, Internalformat_Depth_Size => 16#8275#, Internalformat_Stencil_Size => 16#8276#, Internalformat_Shared_Size => 16#8277#, Internalformat_Red_Type => 16#8278#, Internalformat_Green_Type => 16#8279#, Internalformat_Blue_Type => 16#827A#, Internalformat_Alpha_Type => 16#827B#, Internalformat_Depth_Type => 16#827C#, Internalformat_Stencil_Type => 16#827D#, Max_Width => 16#827E#, Max_Height => 16#827F#, Max_Depth => 16#8280#, Max_Layers => 16#8281#, Max_Combined_Dimensions => 16#8282#, Color_Components => 16#8283#, Depth_Components => 16#8284#, Stencil_Components => 16#8285#, Color_Renderable => 16#8286#, Depth_Renderable => 16#8287#, Stencil_Renderable => 16#8288#, Framebuffer_Renderable => 16#8289#, Framebuffer_Renderable_Layered => 16#828A#, Framebuffer_Blend => 16#828B#, Read_Pixels => 16#828C#, Read_Pixels_Format => 16#828D#, Read_Pixels_Type => 16#828E#, Texture_Image_Format => 16#828F#, Texture_Image_Type => 16#8290#, Get_Texture_Image_Format => 16#8291#, Get_Texture_Image_Type => 16#8292#, Mipmap => 16#8293#, Manual_Generate_Mipmap => 16#8294#, Auto_Generate_Mipmap => 16#8295#, Color_Encoding => 16#8296#, Srgb_Read => 16#8297#, Srgb_Write => 16#8298#, Srgb_Decode_Arb => 16#8299#, Filter => 16#829A#, Vertex_Texture => 16#829B#, Tess_Control_Texture => 16#829C#, Tess_Evaluation_Texture => 16#829D#, Geometry_Texture => 16#829E#, Fragment_Texture => 16#829F#, Compute_Texture => 16#82A0#, Texture_Shadow => 16#82A1#, Texture_Gather => 16#82A2#, Texture_Gather_Shadow => 16#82A3#, Shader_Image_Load => 16#82A4#, Shader_Image_Store => 16#82A5#, Shader_Image_Atomic => 16#82A6#, Image_Texel_Size => 16#82A7#, Image_Compatibility_Class => 16#82A8#, Image_Pixel_Format => 16#82A9#, Image_Pixel_Type => 16#82AA#, Simultaneous_Texture_And_Depth_Test => 16#82AC#, Simultaneous_Texture_And_Stencil_Test => 16#82AD#, Simultaneous_Texture_And_Depth_Write => 16#82AE#, Simultaneous_Texture_And_Stencil_Write => 16#82AF#, Texture_Compressed_Block_Width => 16#82B1#, Texture_Compressed_Block_Height => 16#82B2#, Texture_Compressed_Block_Size => 16#82B3#, Clear_Buffer => 16#82B4#, Texture_View => 16#82B5#, View_Compatibility_Class => 16#82B6#, Texture_Compressed => 16#86A1#, Image_Format_Compatibility_Type => 16#90C7#, Num_Sample_Counts => 16#9380#); for Parameter'Size use Low_Level.Enum'Size; end GL.Enums.Internalformat;
-- Copyright (c) 2018 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. package GL.Enums.Internalformat is pragma Preelaborate; type Parameter is (Samples, Internalformat_Supported, Internalformat_Preferred, Internalformat_Red_Size, Internalformat_Green_Size, Internalformat_Blue_Size, Internalformat_Alpha_Size, Internalformat_Depth_Size, Internalformat_Stencil_Size, Internalformat_Shared_Size, Internalformat_Red_Type, Internalformat_Green_Type, Internalformat_Blue_Type, Internalformat_Alpha_Type, Internalformat_Depth_Type, Internalformat_Stencil_Type, Max_Width, Max_Height, Max_Depth, Max_Layers, Max_Combined_Dimensions, Color_Components, Depth_Components, Stencil_Components, Color_Renderable, Depth_Renderable, Stencil_Renderable, Framebuffer_Renderable, Framebuffer_Renderable_Layered, Framebuffer_Blend, Read_Pixels, Read_Pixels_Format, Read_Pixels_Type, Texture_Image_Format, Texture_Image_Type, Get_Texture_Image_Format, Get_Texture_Image_Type, Mipmap, Manual_Generate_Mipmap, Auto_Generate_Mipmap, Color_Encoding, sRGB_Read, sRGB_Write, sRGB_Decode_ARB, Filter, Vertex_Texture, Tess_Control_Texture, Tess_Evaluation_Texture, Geometry_Texture, Fragment_Texture, Compute_Texture, Texture_Shadow, Texture_Gather, Texture_Gather_Shadow, Shader_Image_Load, Shader_Image_Store, Shader_Image_Atomic, Image_Texel_Size, Image_Compatibility_Class, Image_Pixel_Format, Image_Pixel_Type, Simultaneous_Texture_And_Depth_Test, Simultaneous_Texture_And_Stencil_Test, Simultaneous_Texture_And_Depth_Write, Simultaneous_Texture_And_Stencil_Write, Texture_Compressed_Block_Width, Texture_Compressed_Block_Height, Texture_Compressed_Block_Size, Clear_Buffer, Texture_View, View_Compatibility_Class, Texture_Compressed, Image_Format_Compatibility_Type, Num_Sample_Counts); private for Parameter use (Samples => 16#80A9#, Internalformat_Supported => 16#826F#, Internalformat_Preferred => 16#8270#, Internalformat_Red_Size => 16#8271#, Internalformat_Green_Size => 16#8272#, Internalformat_Blue_Size => 16#8273#, Internalformat_Alpha_Size => 16#8274#, Internalformat_Depth_Size => 16#8275#, Internalformat_Stencil_Size => 16#8276#, Internalformat_Shared_Size => 16#8277#, Internalformat_Red_Type => 16#8278#, Internalformat_Green_Type => 16#8279#, Internalformat_Blue_Type => 16#827A#, Internalformat_Alpha_Type => 16#827B#, Internalformat_Depth_Type => 16#827C#, Internalformat_Stencil_Type => 16#827D#, Max_Width => 16#827E#, Max_Height => 16#827F#, Max_Depth => 16#8280#, Max_Layers => 16#8281#, Max_Combined_Dimensions => 16#8282#, Color_Components => 16#8283#, Depth_Components => 16#8284#, Stencil_Components => 16#8285#, Color_Renderable => 16#8286#, Depth_Renderable => 16#8287#, Stencil_Renderable => 16#8288#, Framebuffer_Renderable => 16#8289#, Framebuffer_Renderable_Layered => 16#828A#, Framebuffer_Blend => 16#828B#, Read_Pixels => 16#828C#, Read_Pixels_Format => 16#828D#, Read_Pixels_Type => 16#828E#, Texture_Image_Format => 16#828F#, Texture_Image_Type => 16#8290#, Get_Texture_Image_Format => 16#8291#, Get_Texture_Image_Type => 16#8292#, Mipmap => 16#8293#, Manual_Generate_Mipmap => 16#8294#, Auto_Generate_Mipmap => 16#8295#, Color_Encoding => 16#8296#, sRGB_Read => 16#8297#, sRGB_Write => 16#8298#, sRGB_Decode_ARB => 16#8299#, Filter => 16#829A#, Vertex_Texture => 16#829B#, Tess_Control_Texture => 16#829C#, Tess_Evaluation_Texture => 16#829D#, Geometry_Texture => 16#829E#, Fragment_Texture => 16#829F#, Compute_Texture => 16#82A0#, Texture_Shadow => 16#82A1#, Texture_Gather => 16#82A2#, Texture_Gather_Shadow => 16#82A3#, Shader_Image_Load => 16#82A4#, Shader_Image_Store => 16#82A5#, Shader_Image_Atomic => 16#82A6#, Image_Texel_Size => 16#82A7#, Image_Compatibility_Class => 16#82A8#, Image_Pixel_Format => 16#82A9#, Image_Pixel_Type => 16#82AA#, Simultaneous_Texture_And_Depth_Test => 16#82AC#, Simultaneous_Texture_And_Stencil_Test => 16#82AD#, Simultaneous_Texture_And_Depth_Write => 16#82AE#, Simultaneous_Texture_And_Stencil_Write => 16#82AF#, Texture_Compressed_Block_Width => 16#82B1#, Texture_Compressed_Block_Height => 16#82B2#, Texture_Compressed_Block_Size => 16#82B3#, Clear_Buffer => 16#82B4#, Texture_View => 16#82B5#, View_Compatibility_Class => 16#82B6#, Texture_Compressed => 16#86A1#, Image_Format_Compatibility_Type => 16#90C7#, Num_Sample_Counts => 16#9380#); for Parameter'Size use Low_Level.Enum'Size; end GL.Enums.Internalformat;
Fix a few compiler style warnings
Fix a few compiler style warnings Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
b91aa794c6ab8c062240601a0fb18c30a3390e6e
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_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 : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_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 : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : 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 : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- The SQL length for strings. Sql_Length : Positive := 255; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; -- The type mapping of the column. Type_Mapping : Gen.Model.Mappings.Mapping_Definition_Access; end record; type Column_Definition_Access is access all Column_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 : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_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 : Association_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Association_Definition); package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; -- Mark flag used by the dependency calculation. Has_Mark : 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 : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Add the SQL length to control the length of some SQL types
Add the SQL length to control the length of some SQL types
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0a6d74bca3c17b3269c83f5f41b57d38035b776a
tests/natools-s_expressions-templates-tests-integers.adb
tests/natools-s_expressions-templates-tests-integers.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.Parsers; with Natools.S_Expressions.Test_Tools; with Natools.S_Expressions.Templates.Integers; with Natools.Static_Maps.S_Expressions.Templates.Integers.T; package body Natools.S_Expressions.Templates.Tests.Integers is procedure Test_Render (Test : in out NT.Test; Defaults : in Templates.Integers.Format; Template : in String; Value : in Integer; Expected : in String); procedure Test_Render (Test : in out NT.Test; Template : in String; Value : in Integer; Expected : in String); -- Run Template with Value and compare the result with Expected ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Test_Render (Test : in out NT.Test; Template : in String; Value : in Integer; Expected : in String) is Input : aliased Test_Tools.Memory_Stream; Output : Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (To_Atom (Template)); Parser.Next; Output.Set_Expected (To_Atom (Expected)); Templates.Integers.Render (Output, Parser, Value); Output.Check_Stream (Test); end Test_Render; procedure Test_Render (Test : in out NT.Test; Defaults : in Templates.Integers.Format; Template : in String; Value : in Integer; Expected : in String) is Input : aliased Test_Tools.Memory_Stream; Output : Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (To_Atom (Template)); Parser.Next; Output.Set_Expected (To_Atom (Expected)); Templates.Integers.Render (Output, Defaults, Parser, Value); Output.Check_Stream (Test); end Test_Render; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Alignment (Report); Default_Format (Report); Explicit_Images (Report); Explicit_Sign (Report); Hexadecimal (Report); Overflow (Report); Parse_Errors (Report); Static_Hash_Map (Report); Explicit_Default_Format (Report); Prefix_And_Suffix (Report); end All_Tests; ----------------------- -- Inidividual Tests -- ----------------------- procedure Alignment (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Debug instantiation"); begin Test_Render (Test, "(width 5)", 0, " 0"); Test_Render (Test, "(width 5)(padding _)(align center)", 10, "_10__"); Test_Render (Test, "(width 5 10)(left-align)", 7, "7 "); Test_Render (Test, "(min-width 5)(right-align)", 2, " 2"); Test_Render (Test, "(width 5)(padding > <)(centered)", 4, ">>4<<"); Test_Render (Test, "(width 5)(left-padding ""["")(right-padding ""]"")(centered)", 126, "[126]"); Test_Render (Test, "(width 3)(centered)", 16, "16 "); Test_Render (Test, "(width 3)(centered)", 456, "456"); Test_Render (Test, "(width 3)(align left)", 567, "567"); Test_Render (Test, "(width 3)(align right)", 678, "678"); exception when Error : others => Test.Report_Exception (Error); end Alignment; procedure Default_Format (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Debug instantiation"); begin Test_Render (Test, "", 42, "42"); exception when Error : others => Test.Report_Exception (Error); end Default_Format; procedure Explicit_Default_Format (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Client-provided default format"); begin declare Default : Templates.Integers.Format; begin Default.Set_Minimum_Width (2); Default.Set_Left_Padding (To_Atom ("0")); Test_Render (Test, Default, "", 5, "05"); Test_Render (Test, Default, "", 12, "12"); Test_Render (Test, Default, "(padding 1: )", 7, " 7"); end; exception when Error : others => Test.Report_Exception (Error); end Explicit_Default_Format; procedure Explicit_Images (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Explicit images in template"); begin Test_Render (Test, "(image (-2 two) (666 evil))", 10, "10"); Test_Render (Test, "(image (-2 two) (666 evil))", -2, "two"); Test_Render (Test, "(image (-2 two) (666 evil))", 666, "evil"); Test_Render (Test, "(image (-2 two) (666 evil) (-2))", -2, "-2"); Test_Render (Test, "(image (1 one))3:Two4:four", 1, "one"); Test_Render (Test, "(image (1 one))3:Two4:four", 2, "Two"); Test_Render (Test, "(image (1 one))3:Two4:four", 3, "four"); Test_Render (Test, "(image (1 one))3:Two4:four", 4, "4"); Test_Render (Test, "(image (invalid -))5:first", Integer'First, "first"); exception when Error : others => Test.Report_Exception (Error); end Explicit_Images; procedure Explicit_Sign (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Explicit sign specification"); begin Test_Render (Test, "(sign +)", 42, "+42"); Test_Render (Test, "(sign + _)", 42, "+42"); Test_Render (Test, "(sign + _)", -42, "_42"); exception when Error : others => Test.Report_Exception (Error); end Explicit_Sign; procedure Hexadecimal (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Hexadecimal representation"); Hex_Spec : constant String := "(base 0 1 2 3 4 5 6 7 8 9 A B C D E F)"; begin Test_Render (Test, Hex_Spec, 8, "8"); Test_Render (Test, Hex_Spec, 16#BEE#, "BEE"); exception when Error : others => Test.Report_Exception (Error); end Hexadecimal; procedure Overflow (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Width overflow"); begin Test_Render (Test, "(width 3)", 10_000, ""); Test_Render (Test, "(max-width 4)", 10_000, ""); Test_Render (Test, "(max-width 3 ""[...]"")", 10_000, "[...]"); Test_Render (Test, "(width 2 3 ...)", 10_000, "..."); exception when Error : others => Test.Report_Exception (Error); end Overflow; procedure Parse_Errors (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); begin Test_Render (Test, "(invalid-command)", 1, "1"); Test_Render (Test, "(align)", 2, "2"); Test_Render (Test, "(align invalid)", 3, "3"); Test_Render (Test, "(padding)", 4, "4"); Test_Render (Test, "(left-padding)", 5, "5"); Test_Render (Test, "(right-padding)", 6, "6"); Test_Render (Test, "(signs)", 7, "7"); Test_Render (Test, "(width)", 8, "8"); Test_Render (Test, "(max-width)", 9, "9"); Test_Render (Test, "(min-width)", 10, "10"); exception when Error : others => Test.Report_Exception (Error); end Parse_Errors; procedure Prefix_And_Suffix (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); Ordinal : constant String := "(suffix 1:? (th (0 31)) (st 1 21 31) (nd 2 22) (rd 3 23) (0: 0))"; begin declare Format : Templates.Integers.Format; begin Format.Set_Prefix ((0, 9), To_Atom ("a")); Format.Set_Prefix ((-99, -10), To_Atom ("b")); Format.Set_Prefix ((50, 99), To_Atom ("c")); Format.Set_Prefix (0, To_Atom ("d")); Format.Set_Prefix (-10, To_Atom ("e")); Format.Set_Prefix (5, To_Atom ("f")); Format.Set_Prefix ((7, 52), To_Atom ("g")); Format.Set_Prefix ((-52, -49), To_Atom ("h")); Format.Set_Prefix ((-100, -90), To_Atom ("i")); Format.Remove_Prefix (8); Test_Render (Test, Format, "", -196, "-196"); Test_Render (Test, Format, "", -101, "-101"); Test_Render (Test, Format, "", -100, "i-100"); Test_Render (Test, Format, "", -90, "i-90"); Test_Render (Test, Format, "", -89, "b-89"); Test_Render (Test, Format, "", -53, "b-53"); Test_Render (Test, Format, "", -52, "h-52"); Test_Render (Test, Format, "", -49, "h-49"); Test_Render (Test, Format, "", -48, "b-48"); Test_Render (Test, Format, "", -11, "b-11"); Test_Render (Test, Format, "", -10, "e-10"); Test_Render (Test, Format, "", -9, "-9"); Test_Render (Test, Format, "", -1, "-1"); Test_Render (Test, Format, "", 0, "d0"); Test_Render (Test, Format, "", 1, "a1"); Test_Render (Test, Format, "", 4, "a4"); Test_Render (Test, Format, "", 5, "f5"); Test_Render (Test, Format, "", 6, "a6"); Test_Render (Test, Format, "", 7, "g7"); Test_Render (Test, Format, "", 8, "8"); Test_Render (Test, Format, "", 9, "g9"); Test_Render (Test, Format, "", 52, "g52"); Test_Render (Test, Format, "", 53, "c53"); Test_Render (Test, Format, "", 99, "c99"); Test_Render (Test, Format, "", 100, "100"); Test_Render (Test, Format, "", 192, "192"); end; declare Format : Templates.Integers.Format; begin Format.Set_Suffix ((0, 10), To_Atom ("th")); Format.Set_Suffix (1, To_Atom ("st")); Format.Remove_Suffix (0); Test_Render (Test, Format, "", -1, "-1"); Test_Render (Test, Format, "", 0, "0"); Test_Render (Test, Format, "", 1, "1st"); Test_Render (Test, Format, "", 4, "4th"); Test_Render (Test, Format, "", 10, "10th"); end; Test_Render (Test, Ordinal, -1, "-1?"); Test_Render (Test, Ordinal, 0, "0"); Test_Render (Test, Ordinal, 1, "1st"); Test_Render (Test, Ordinal, 2, "2nd"); Test_Render (Test, Ordinal, 3, "3rd"); Test_Render (Test, Ordinal, 4, "4th"); Test_Render (Test, "(prefix (a) (b invalid (9 5)))", 0, "0"); Test_Render (Test, "(prefix (c (invalid 5) (-1 invalid)))", 0, "0"); Test_Render (Test, "(prefix (d ((invalid) 5) (-1)) ())", 0, "0"); declare Format : Templates.Integers.Format; begin Format.Set_Minimum_Width (10); Format.Set_Suffix (1, To_Atom ("<sup>er</sup>"), 2); Format.Set_Prefix (10, To_Atom ("dix : ")); Test_Render (Test, Format, "", 5, " 5"); Test_Render (Test, Format, "", 1, " 1<sup>er</sup>"); Test_Render (Test, Format, "(centered)", 10, " dix : 10 "); Test_Render (Test, Format, "(suffix ((th 0) 7))", 7, " 7th"); end; exception when Error : others => Test.Report_Exception (Error); end Prefix_And_Suffix; procedure Static_Hash_Map (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); begin if not Natools.Static_Maps.S_Expressions.Templates.Integers.T then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Static_Hash_Map; end Natools.S_Expressions.Templates.Tests.Integers;
------------------------------------------------------------------------------ -- 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.Parsers; with Natools.S_Expressions.Test_Tools; with Natools.S_Expressions.Templates.Integers; with Natools.Static_Maps.S_Expressions.Templates.Integers.T; package body Natools.S_Expressions.Templates.Tests.Integers is procedure Test_Render (Test : in out NT.Test; Defaults : in Templates.Integers.Format; Template : in String; Value : in Integer; Expected : in String); procedure Test_Render (Test : in out NT.Test; Template : in String; Value : in Integer; Expected : in String); -- Run Template with Value and compare the result with Expected ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Test_Render (Test : in out NT.Test; Template : in String; Value : in Integer; Expected : in String) is Input : aliased Test_Tools.Memory_Stream; Output : Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (To_Atom (Template)); Parser.Next; Output.Set_Expected (To_Atom (Expected)); Templates.Integers.Render (Output, Parser, Value); Output.Check_Stream (Test); end Test_Render; procedure Test_Render (Test : in out NT.Test; Defaults : in Templates.Integers.Format; Template : in String; Value : in Integer; Expected : in String) is Input : aliased Test_Tools.Memory_Stream; Output : Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (To_Atom (Template)); Parser.Next; Output.Set_Expected (To_Atom (Expected)); Templates.Integers.Render (Output, Defaults, Parser, Value); Output.Check_Stream (Test); end Test_Render; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Alignment (Report); Default_Format (Report); Explicit_Images (Report); Explicit_Sign (Report); Hexadecimal (Report); Overflow (Report); Parse_Errors (Report); Static_Hash_Map (Report); Explicit_Default_Format (Report); Prefix_And_Suffix (Report); end All_Tests; ----------------------- -- Inidividual Tests -- ----------------------- procedure Alignment (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Debug instantiation"); begin Test_Render (Test, "(width 5)", 0, " 0"); Test_Render (Test, "(width 5)(padding _)(align center)", 10, "_10__"); Test_Render (Test, "(width 5 10)(left-align)", 7, "7 "); Test_Render (Test, "(min-width 5)(right-align)", 2, " 2"); Test_Render (Test, "(width 5)(padding > <)(centered)", 4, ">>4<<"); Test_Render (Test, "(width 5)(left-padding ""["")(right-padding ""]"")(centered)", 126, "[126]"); Test_Render (Test, "(width 3)(centered)", 16, "16 "); Test_Render (Test, "(width 3)(centered)", 456, "456"); Test_Render (Test, "(width 3)(align left)", 567, "567"); Test_Render (Test, "(width 3)(align right)", 678, "678"); exception when Error : others => Test.Report_Exception (Error); end Alignment; procedure Default_Format (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Debug instantiation"); begin Test_Render (Test, "", 42, "42"); exception when Error : others => Test.Report_Exception (Error); end Default_Format; procedure Explicit_Default_Format (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Client-provided default format"); begin declare Default : Templates.Integers.Format; begin Default.Set_Minimum_Width (2); Default.Set_Left_Padding (To_Atom ("0")); Test_Render (Test, Default, "", 5, "05"); Test_Render (Test, Default, "", 12, "12"); Test_Render (Test, Default, "(padding 1: )", 7, " 7"); end; exception when Error : others => Test.Report_Exception (Error); end Explicit_Default_Format; procedure Explicit_Images (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Explicit images in template"); begin Test_Render (Test, "(image (-2 two) (666 evil))", 10, "10"); Test_Render (Test, "(image (-2 two) (666 evil))", -2, "two"); Test_Render (Test, "(image (-2 two) (666 evil))", 666, "evil"); Test_Render (Test, "(image (-2 two) (666 evil) (-2))", -2, "-2"); Test_Render (Test, "(image (1 one))3:Two4:four", 1, "one"); Test_Render (Test, "(image (1 one))3:Two4:four", 2, "Two"); Test_Render (Test, "(image (1 one))3:Two4:four", 3, "four"); Test_Render (Test, "(image (1 one))3:Two4:four", 4, "4"); Test_Render (Test, "(image (invalid -))5:first", Integer'First, "first"); Test_Render (Test, "(image-range (""?"" (10 19)))", 9, "9"); Test_Render (Test, "(image-range (""?"" (10 19)))", 10, "?"); Test_Render (Test, "(image-range (""?"" (10 19)))", 15, "?"); Test_Render (Test, "(image-range (""?"" (10 19)))", 19, "?"); Test_Render (Test, "(image-range (""?"" (10 19)))", 20, "20"); exception when Error : others => Test.Report_Exception (Error); end Explicit_Images; procedure Explicit_Sign (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Explicit sign specification"); begin Test_Render (Test, "(sign +)", 42, "+42"); Test_Render (Test, "(sign + _)", 42, "+42"); Test_Render (Test, "(sign + _)", -42, "_42"); exception when Error : others => Test.Report_Exception (Error); end Explicit_Sign; procedure Hexadecimal (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Hexadecimal representation"); Hex_Spec : constant String := "(base 0 1 2 3 4 5 6 7 8 9 A B C D E F)"; begin Test_Render (Test, Hex_Spec, 8, "8"); Test_Render (Test, Hex_Spec, 16#BEE#, "BEE"); exception when Error : others => Test.Report_Exception (Error); end Hexadecimal; procedure Overflow (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Width overflow"); begin Test_Render (Test, "(width 3)", 10_000, ""); Test_Render (Test, "(max-width 4)", 10_000, ""); Test_Render (Test, "(max-width 3 ""[...]"")", 10_000, "[...]"); Test_Render (Test, "(width 2 3 ...)", 10_000, "..."); exception when Error : others => Test.Report_Exception (Error); end Overflow; procedure Parse_Errors (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); begin Test_Render (Test, "(invalid-command)", 1, "1"); Test_Render (Test, "(align)", 2, "2"); Test_Render (Test, "(align invalid)", 3, "3"); Test_Render (Test, "(padding)", 4, "4"); Test_Render (Test, "(left-padding)", 5, "5"); Test_Render (Test, "(right-padding)", 6, "6"); Test_Render (Test, "(signs)", 7, "7"); Test_Render (Test, "(width)", 8, "8"); Test_Render (Test, "(max-width)", 9, "9"); Test_Render (Test, "(min-width)", 10, "10"); exception when Error : others => Test.Report_Exception (Error); end Parse_Errors; procedure Prefix_And_Suffix (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); Ordinal : constant String := "(suffix 1:? (th (0 31)) (st 1 21 31) (nd 2 22) (rd 3 23) (0: 0))"; begin declare Format : Templates.Integers.Format; begin Format.Set_Prefix ((0, 9), To_Atom ("a")); Format.Set_Prefix ((-99, -10), To_Atom ("b")); Format.Set_Prefix ((50, 99), To_Atom ("c")); Format.Set_Prefix (0, To_Atom ("d")); Format.Set_Prefix (-10, To_Atom ("e")); Format.Set_Prefix (5, To_Atom ("f")); Format.Set_Prefix ((7, 52), To_Atom ("g")); Format.Set_Prefix ((-52, -49), To_Atom ("h")); Format.Set_Prefix ((-100, -90), To_Atom ("i")); Format.Remove_Prefix (8); Test_Render (Test, Format, "", -196, "-196"); Test_Render (Test, Format, "", -101, "-101"); Test_Render (Test, Format, "", -100, "i-100"); Test_Render (Test, Format, "", -90, "i-90"); Test_Render (Test, Format, "", -89, "b-89"); Test_Render (Test, Format, "", -53, "b-53"); Test_Render (Test, Format, "", -52, "h-52"); Test_Render (Test, Format, "", -49, "h-49"); Test_Render (Test, Format, "", -48, "b-48"); Test_Render (Test, Format, "", -11, "b-11"); Test_Render (Test, Format, "", -10, "e-10"); Test_Render (Test, Format, "", -9, "-9"); Test_Render (Test, Format, "", -1, "-1"); Test_Render (Test, Format, "", 0, "d0"); Test_Render (Test, Format, "", 1, "a1"); Test_Render (Test, Format, "", 4, "a4"); Test_Render (Test, Format, "", 5, "f5"); Test_Render (Test, Format, "", 6, "a6"); Test_Render (Test, Format, "", 7, "g7"); Test_Render (Test, Format, "", 8, "8"); Test_Render (Test, Format, "", 9, "g9"); Test_Render (Test, Format, "", 52, "g52"); Test_Render (Test, Format, "", 53, "c53"); Test_Render (Test, Format, "", 99, "c99"); Test_Render (Test, Format, "", 100, "100"); Test_Render (Test, Format, "", 192, "192"); end; declare Format : Templates.Integers.Format; begin Format.Set_Suffix ((0, 10), To_Atom ("th")); Format.Set_Suffix (1, To_Atom ("st")); Format.Remove_Suffix (0); Test_Render (Test, Format, "", -1, "-1"); Test_Render (Test, Format, "", 0, "0"); Test_Render (Test, Format, "", 1, "1st"); Test_Render (Test, Format, "", 4, "4th"); Test_Render (Test, Format, "", 10, "10th"); end; Test_Render (Test, Ordinal, -1, "-1?"); Test_Render (Test, Ordinal, 0, "0"); Test_Render (Test, Ordinal, 1, "1st"); Test_Render (Test, Ordinal, 2, "2nd"); Test_Render (Test, Ordinal, 3, "3rd"); Test_Render (Test, Ordinal, 4, "4th"); Test_Render (Test, "(prefix (a) (b invalid (9 5)))", 0, "0"); Test_Render (Test, "(prefix (c (invalid 5) (-1 invalid)))", 0, "0"); Test_Render (Test, "(prefix (d ((invalid) 5) (-1)) ())", 0, "0"); declare Format : Templates.Integers.Format; begin Format.Set_Minimum_Width (10); Format.Set_Suffix (1, To_Atom ("<sup>er</sup>"), 2); Format.Set_Prefix (10, To_Atom ("dix : ")); Test_Render (Test, Format, "", 5, " 5"); Test_Render (Test, Format, "", 1, " 1<sup>er</sup>"); Test_Render (Test, Format, "(centered)", 10, " dix : 10 "); Test_Render (Test, Format, "(suffix ((th 0) 7))", 7, " 7th"); end; exception when Error : others => Test.Report_Exception (Error); end Prefix_And_Suffix; procedure Static_Hash_Map (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parse errors in template"); begin if not Natools.Static_Maps.S_Expressions.Templates.Integers.T then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Static_Hash_Map; end Natools.S_Expressions.Templates.Tests.Integers;
add tests for image ranges
s_expressions-templates-tests-integers: add tests for image ranges
Ada
isc
faelys/natools
47dddbaf3cef932c80c7034d966a95a4c8110518
src/mysql/mysql-time.ads
src/mysql/mysql-time.ads
with Interfaces.C; use Interfaces.C; with Mysql.Mysql; use Mysql.Mysql; package Mysql.Time is pragma Preelaborate; -- Copyright (C) 2004 MySQL AB -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 2 of the License. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- Time declarations shared between the server and client API: -- you should not add anything to this header unless it's used -- (and hence should be visible) in mysql.h. -- If you're looking for a place to add new time-related declaration, -- it's most likely my_time.h. See also "C API Handling of Date -- and Time Values" chapter in documentation. -- subtype enum_mysql_timestamp_type is unsigned; MYSQL_TIMESTAMP_NONE : constant enum_mysql_timestamp_type := -2; MYSQL_TIMESTAMP_ERROR : constant enum_mysql_timestamp_type := -1; MYSQL_TIMESTAMP_DATE : constant enum_mysql_timestamp_type := 0; MYSQL_TIMESTAMP_DATETIME : constant enum_mysql_timestamp_type := 1; MYSQL_TIMESTAMP_TIME : constant enum_mysql_timestamp_type := 2; -- Structure which is used to represent datetime values inside MySQL. -- We assume that values in this structure are normalized, i.e. year <= 9999, -- month <= 12, day <= 31, hour <= 23, hour <= 59, hour <= 59. Many functions -- in server such as my_system_gmt_sec() or make_time() family of functions -- rely on this (actually now usage of make_*() family relies on a bit weaker -- restriction). Also functions that produce MYSQL_TIME as result ensure this. -- There is one exception to this rule though if this structure holds time -- value (time_type == MYSQL_TIMESTAMP_TIME) days and hour member can hold -- bigger values. -- type st_mysql_time is record year : aliased unsigned; month : aliased unsigned; day : aliased unsigned; hour : aliased unsigned; minute : aliased unsigned; second : aliased unsigned; second_part : aliased unsigned_long; neg : aliased my_bool; time_type : aliased enum_mysql_timestamp_type; end record; pragma Convention (C, st_mysql_time); subtype MYSQL_TIME is st_mysql_time; end Mysql.Time;
with Interfaces.C; use Interfaces.C; with Mysql.Mysql; use Mysql.Mysql; package Mysql.Time is pragma Preelaborate; -- Copyright (C) 2004 MySQL AB -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 2 of the License. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- Time declarations shared between the server and client API: -- you should not add anything to this header unless it's used -- (and hence should be visible) in mysql.h. -- If you're looking for a place to add new time-related declaration, -- it's most likely my_time.h. See also "C API Handling of Date -- and Time Values" chapter in documentation. -- subtype enum_mysql_timestamp_type is unsigned; MYSQL_TIMESTAMP_NONE : constant enum_mysql_timestamp_type := 16#fffffffe#; MYSQL_TIMESTAMP_ERROR : constant enum_mysql_timestamp_type := 16#ffffffff#; MYSQL_TIMESTAMP_DATE : constant enum_mysql_timestamp_type := 0; MYSQL_TIMESTAMP_DATETIME : constant enum_mysql_timestamp_type := 1; MYSQL_TIMESTAMP_TIME : constant enum_mysql_timestamp_type := 2; -- Structure which is used to represent datetime values inside MySQL. -- We assume that values in this structure are normalized, i.e. year <= 9999, -- month <= 12, day <= 31, hour <= 23, hour <= 59, hour <= 59. Many functions -- in server such as my_system_gmt_sec() or make_time() family of functions -- rely on this (actually now usage of make_*() family relies on a bit weaker -- restriction). Also functions that produce MYSQL_TIME as result ensure this. -- There is one exception to this rule though if this structure holds time -- value (time_type == MYSQL_TIMESTAMP_TIME) days and hour member can hold -- bigger values. -- type st_mysql_time is record year : aliased unsigned; month : aliased unsigned; day : aliased unsigned; hour : aliased unsigned; minute : aliased unsigned; second : aliased unsigned; second_part : aliased unsigned_long; neg : aliased my_bool; time_type : aliased enum_mysql_timestamp_type; end record; pragma Convention (C, st_mysql_time); subtype MYSQL_TIME is st_mysql_time; end Mysql.Time;
Fix compilation warning that was not detected for several years!
Fix compilation warning that was not detected for several years!
Ada
apache-2.0
stcarrez/ada-ado
7fd63132353d8ec72efac491f837e9abdaf62295
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return "role"; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Set_Reader_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Set_Reader_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return "role"; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Rename Set_Reader_Config into Prepare_Config
Rename Set_Reader_Config into Prepare_Config
Ada
apache-2.0
stcarrez/ada-security
c41f33e689fd458ee6c6bbf189c937594dab0a70
ARM/STMicro/STM32/boards/stm32f7_discovery/stm32-board.ads
ARM/STMicro/STM32/boards/stm32f7_discovery/stm32-board.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F7 Discovery kits -- manufactured by ST Microelectronics. with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; -- with STM32.SPI; use STM32.SPI; with STM32.ADC; use STM32.ADC; with STM32.FMC; use STM32.FMC; with Ada.Interrupts.Names; use Ada.Interrupts; use STM32; -- for base addresses package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; Green : User_LED renames PI1; All_LEDs : constant GPIO_Points := (1 => Green); LCH_LED : constant User_LED := Green; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : User_LED) renames STM32.GPIO.Set; procedure Turn_Off (This : User_LED) renames STM32.GPIO.Clear; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LEDs (These : GPIO_Points) renames STM32.GPIO.Toggle; -- GPIO Pins for FMC FMC_A : constant GPIO_Points := (PF0, PF1, PF2, PF3, PF4, PF5, PF12, PF13, PF14, PF15, PG0, PG1); FMC_D : constant GPIO_Points := (PD14, PD15, PD0, PD1, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15, PD8, PD9, PD10); FMC_SDNWE : GPIO_Point renames PH5; FMC_SDNRAS : GPIO_Point renames PF11; FMC_SDNCAS : GPIO_Point renames PG15; FMC_SDCLK : GPIO_Point renames PG8; FMC_BA0 : GPIO_Point renames PG4; FMC_BA1 : GPIO_Point renames PG5; FMC_SDNE0 : GPIO_Point renames PH3; FMC_SDCKE0 : GPIO_Point renames PC3; FMC_NBL0 : GPIO_Point renames PE0; FMC_NBL1 : GPIO_Point renames PE1; SDRAM_PINS : constant GPIO_Points := FMC_A & FMC_D & FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK & FMC_BA0 & FMC_BA1 & FMC_SDNE0 & FMC_SDCKE0 & FMC_NBL0 & FMC_NBL1; -- SDRAM CONFIGURATION Parameters SDRAM_Base : constant := 16#C0000000#; SDRAM_Size : constant := 16#800000#; SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank := STM32.FMC.FMC_Bank1_SDRAM; SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width := STM32.FMC.FMC_SDMemory_Width_16b; SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits := STM32.FMC.FMC_RowBits_Number_12b; SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency := STM32.FMC.FMC_CAS_Latency_2; SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration := STM32.FMC.FMC_SDClock_Period_2; SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read := STM32.FMC.FMC_Read_Burst_Disable; SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay := STM32.FMC.FMC_ReadPipe_Delay_0; SDRAM_Refresh_Cnt : constant := 1539; ------------------------ -- GPIO Pins for LCD -- ------------------------ LCD_BL_CTRL : GPIO_Point renames PK3; LCD_ENABLE : GPIO_Point renames PI12; LCD_HSYNC : GPIO_Point renames PI10; LCD_VSYNC : GPIO_Point renames PI9; LCD_CLK : GPIO_Point renames PI14; LCD_DE : GPIO_Point renames PK7; LCD_INT : GPIO_Point renames PI13; LCD_SDA : GPIO_Point renames PH8; LCD_SCL : GPIO_Point renames PH7; NC1 : GPIO_Point renames PI8; LCD_CTRL_PINS : constant GPIO_Points := (LCD_VSYNC, LCD_HSYNC, LCD_INT, LCD_CLK, LCD_DE, NC1); LCD_RGB_AF14 : constant GPIO_Points := (PI15, PJ0, PJ1, PJ2, PJ3, PJ4, PJ5, PJ6, -- Red PJ7, PJ8, PJ9, PJ10, PJ11, PK0, PK1, PK2, -- Green PE4, PJ13, PJ14, PJ15, PK4, PK5, PK6); -- Blue LCD_RGB_AF9 : constant GPIO_Points := (1 => PG12); -- B4 TP_Pins : constant GPIO_Points := (LCD_SDA, LCD_SCL); -- User button User_Button_Point : GPIO_Point renames PA0; User_Button_Interrupt : constant Interrupt_Id := Names.EXTI0_Interrupt; procedure Configure_User_Button_GPIO; -- Configures the GPIO port/pin for the blue user button. Sufficient -- for polling the button, and necessary for having the button generate -- interrupts. end STM32.Board;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F7 Discovery kits -- manufactured by ST Microelectronics. with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; -- with STM32.SPI; use STM32.SPI; with STM32.ADC; use STM32.ADC; with STM32.FMC; use STM32.FMC; with Ada.Interrupts.Names; use Ada.Interrupts; use STM32; -- for base addresses package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; Green : User_LED renames PI1; All_LEDs : constant GPIO_Points := (1 => Green); LCH_LED : constant User_LED := Green; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : User_LED) renames STM32.GPIO.Set; procedure Turn_Off (This : User_LED) renames STM32.GPIO.Clear; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LEDs (These : GPIO_Points) renames STM32.GPIO.Toggle; -- GPIO Pins for FMC FMC_A : constant GPIO_Points := (PF0, PF1, PF2, PF3, PF4, PF5, PF12, PF13, PF14, PF15, PG0, PG1); FMC_D : constant GPIO_Points := (PD14, PD15, PD0, PD1, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15, PD8, PD9, PD10); FMC_SDNWE : GPIO_Point renames PH5; FMC_SDNRAS : GPIO_Point renames PF11; FMC_SDNCAS : GPIO_Point renames PG15; FMC_SDCLK : GPIO_Point renames PG8; FMC_BA0 : GPIO_Point renames PG4; FMC_BA1 : GPIO_Point renames PG5; FMC_SDNE0 : GPIO_Point renames PH3; FMC_SDCKE0 : GPIO_Point renames PC3; FMC_NBL0 : GPIO_Point renames PE0; FMC_NBL1 : GPIO_Point renames PE1; SDRAM_PINS : constant GPIO_Points := FMC_A & FMC_D & FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK & FMC_BA0 & FMC_BA1 & FMC_SDNE0 & FMC_SDCKE0 & FMC_NBL0 & FMC_NBL1; -- SDRAM CONFIGURATION Parameters SDRAM_Base : constant := 16#C0000000#; SDRAM_Size : constant := 16#800000#; SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank := STM32.FMC.FMC_Bank1_SDRAM; SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width := STM32.FMC.FMC_SDMemory_Width_16b; SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits := STM32.FMC.FMC_RowBits_Number_12b; SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency := STM32.FMC.FMC_CAS_Latency_2; SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration := STM32.FMC.FMC_SDClock_Period_2; SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read := STM32.FMC.FMC_Read_Burst_Disable; SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay := STM32.FMC.FMC_ReadPipe_Delay_0; SDRAM_Refresh_Cnt : constant := 1539; ------------------------ -- GPIO Pins for LCD -- ------------------------ LCD_BL_CTRL : GPIO_Point renames PK3; LCD_ENABLE : GPIO_Point renames PI12; LCD_HSYNC : GPIO_Point renames PI10; LCD_VSYNC : GPIO_Point renames PI9; LCD_CLK : GPIO_Point renames PI14; LCD_DE : GPIO_Point renames PK7; LCD_INT : GPIO_Point renames PI13; LCD_SDA : GPIO_Point renames PH8; LCD_SCL : GPIO_Point renames PH7; NC1 : GPIO_Point renames PI8; LCD_CTRL_PINS : constant GPIO_Points := (LCD_VSYNC, LCD_HSYNC, LCD_INT, LCD_CLK, LCD_DE, NC1); LCD_RGB_AF14 : constant GPIO_Points := (PI15, PJ0, PJ1, PJ2, PJ3, PJ4, PJ5, PJ6, -- Red PJ7, PJ8, PJ9, PJ10, PJ11, PK0, PK1, PK2, -- Green PE4, PJ13, PJ14, PJ15, PK4, PK5, PK6); -- Blue LCD_RGB_AF9 : constant GPIO_Points := (1 => PG12); -- B4 TP_Pins : constant GPIO_Points := (LCD_SDA, LCD_SCL); -- User button User_Button_Point : GPIO_Point renames PI11; User_Button_Interrupt : constant Interrupt_Id := Names.EXTI15_10_Interrupt; procedure Configure_User_Button_GPIO; -- Configures the GPIO port/pin for the blue user button. Sufficient -- for polling the button, and necessary for having the button generate -- interrupts. end STM32.Board;
Fix the user button definition for the STM32F7-Disco.
Fix the user button definition for the STM32F7-Disco.
Ada
bsd-3-clause
ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
425508b14eeb509a81e7dea67a4113a2846bf4b9
matp/src/mat-formats.adb
matp/src/mat-formats.adb
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => if Mode = BRIEF then return "malloc"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.Targets.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc"; else return "realloc"; end if; else if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ") = " & Addr (Item.Addr); else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; end if; when MAT.Events.Targets.MSG_FREE => if Mode = BRIEF then return "free"; else return "free(" & Addr (Item.Addr) & ")"; end if; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; package body MAT.Formats is use type MAT.Types.Target_Tick_Ref; Hex_Prefix : Boolean := True; Conversion : constant String (1 .. 10) := "0123456789"; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- Format the address into a string. -- ------------------------------ function Addr (Value : in MAT.Types.Target_Addr) return String is Hex : constant String := MAT.Types.Hex_Image (Value); begin if Hex_Prefix then return "0x" & Hex; else return Hex; end if; end Addr; -- ------------------------------ -- Format the size into a string. -- ------------------------------ function Size (Value : in MAT.Types.Target_Size) return String is Result : constant String := MAT.Types.Target_Size'Image (Value); begin if Result (Result'First) = ' ' then return Result (Result'First + 1 .. Result'Last); else return Result; end if; end Size; -- ------------------------------ -- Format the time relative to the start time. -- ------------------------------ function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String is T : constant MAT.Types.Target_Tick_Ref := Value - Start; Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000; Msec : Natural := Natural (Usec / 1_000); Frac : String (1 .. 5); begin Frac (5) := 's'; Frac (4) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (3) := Conversion (Msec mod 10 + 1); Msec := Msec / 10; Frac (2) := Conversion (Msec mod 10 + 1); Frac (1) := '.'; return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac; end Time; -- ------------------------------ -- Format the duration in seconds, milliseconds or microseconds. -- ------------------------------ function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000; Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000; Msec : constant Natural := Natural (Usec / 1_000); Val : Natural; Frac : String (1 .. 5); begin if Sec = 0 and Msec = 0 then return Util.Strings.Image (Integer (Usec)) & "us"; elsif Sec = 0 then Val := Natural (Usec mod 1_000); Frac (5) := 's'; Frac (4) := 'm'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Msec)) & Frac; else Val := Msec; Frac (4) := 's'; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (3) := Conversion (Val mod 10 + 1); Val := Val / 10; Frac (2) := Conversion (Val mod 10 + 1); Frac (1) := '.'; return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4); end if; end Duration; function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward); Len : constant Natural := Ada.Strings.Unbounded.Length (File); begin if Pos /= 0 then return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len); else return Ada.Strings.Unbounded.To_String (File); end if; end Location; -- ------------------------------ -- Format a file, line, function information into a string. -- ------------------------------ function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (File) = 0 then return Ada.Strings.Unbounded.To_String (Func); elsif Line > 0 then declare Num : constant String := Natural'Image (Line); begin return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")"; end; else return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")"; end if; end Location; -- ------------------------------ -- Format an event range description. -- ------------------------------ function Event (First : in MAT.Events.Targets.Probe_Event_Type; Last : in MAT.Events.Targets.Probe_Event_Type) return String is use type MAT.Events.Targets.Event_Id_Type; Id1 : constant String := MAT.Events.Targets.Event_Id_Type'Image (First.Id); Id2 : constant String := MAT.Events.Targets.Event_Id_Type'Image (Last.Id); begin if First.Id = Last.Id then return Id1 (Id1'First + 1 .. Id1'Last); else return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last); end if; end Event; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Mode : in Format_Type := NORMAL) return String is use type MAT.Types.Target_Addr; begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => if Mode = BRIEF then return "malloc"; else return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; when MAT.Events.Targets.MSG_REALLOC => if Mode = BRIEF then if Item.Old_Addr = 0 then return "realloc"; else return "realloc"; end if; else if Item.Old_Addr = 0 then return "realloc(0," & Size (Item.Size) & ") = " & Addr (Item.Addr); else return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); end if; end if; when MAT.Events.Targets.MSG_FREE => if Mode = BRIEF then return "free"; else return "free(" & Addr (Item.Addr) & ")"; end if; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_FREE); return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time) & ", freed " & Duration (Free_Event.Time - Item.Time) & " after by event" & MAT.Events.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.MSG_MALLOC); return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time) & ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time) & " by event" & MAT.Events.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
Implement the Event function to print an event range
Implement the Event function to print an event range
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2adc8c3d6db5d64c2fb6bc462481b9a13439a67c
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, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders; -- == Encoder Streams == -- The `Util.Streams.Buffered.Encoders` is a generic package which implements an -- encoding or decoding stream through the `Transformer` interface. The generic -- package must be instantiated with a transformer type. The stream passes the data -- to be written to the `Transform` method of that interface and it makes -- transformations on the data before being written. -- -- The AES encoding stream is created as follows: -- -- package Encoding is -- new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Encoder); -- -- and the AES decoding stream is created with: -- -- package Decoding is -- new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Decoder); -- -- 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 `Initialize` 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.Input_Output_Buffer_Stream with record Transform : Encoder; Flushed : Boolean := False; end record; -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Encoder_Stream; Size : in Positive); -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. procedure Produces (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Initialize the stream to read the given streams. procedure Consumes (Stream : in out Encoder_Stream; Input : access Input_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); -- 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 Encoder_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- 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); overriding procedure Finalize (Stream : in out Encoder_Stream); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Encoder_Stream); end Util.Streams.Buffered.Encoders;
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2019, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders; -- == Encoder Streams == -- The `Util.Streams.Buffered.Encoders` is a generic package which implements an -- encoding or decoding stream through the `Transformer` interface. The generic -- package must be instantiated with a transformer type. The stream passes the data -- to be written to the `Transform` method of that interface and it makes -- transformations on the data before being written. -- -- The AES encoding stream is created as follows: -- -- package Encoding is -- new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Encoder); -- -- and the AES decoding stream is created with: -- -- package Decoding is -- new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Decoder); -- -- The encoding stream instance is declared: -- -- Encode : Util.Streams.Buffered.Encoders.Encoder_Stream; -- -- The encoding stream manages a buffer that is used to hold the encoded data before it is -- written to the target stream. The `Initialize` 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"); -- -- The encoding stream provides a `Produces` procedure that reads the encoded -- stream and write the result in another stream. It also provides a `Consumes` -- procedure that encodes a stream by reading its content and write the encoded -- result to another stream. 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.Input_Output_Buffer_Stream with record Transform : Encoder; Flushed : Boolean := False; end record; -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Encoder_Stream; Size : in Positive); -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. procedure Produces (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Initialize the stream to read the given streams. procedure Consumes (Stream : in out Encoder_Stream; Input : access Input_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); -- 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 Encoder_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- 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); overriding procedure Finalize (Stream : in out Encoder_Stream); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Encoder_Stream); end Util.Streams.Buffered.Encoders;
Fix the documentation
Fix the documentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7f79d96200a90355c13dfb939192815bea5d862f
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 Util.Strings; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; package body AWA.Blogs.Tests is 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.Create_Blog", Test_Create_Blog'Access); end Add_Tests; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; 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"); declare R : constant String := Reply.Get_Header ("Location"); Pos : constant Natural := Util.Strings.Rindex (R, '='); begin T.Assert (Pos > 0, "Invalid redirect response"); ASF.Tests.Assert_Redirect (T, "/asfunit/blogs/admin/create.html?id=" & R (Pos + 1 .. R'Last), Reply, "Invalid redirect after blog creation"); Request.Set_Parameter ("post-blog-id", R (Pos + 1 .. R'Last)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", "the-blog-url"); 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.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); ASF.Tests.Assert_Redirect (T, "/asfunit/blogs/admin/list.html?blog_id=" & R (Pos + 1 .. R'Last), Reply, "Invalid redirect after blog post creation"); end; end Test_Create_Blog; end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- 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 Util.Strings; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; 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.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'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; end AWA.Blogs.Tests;
Implement new tests to verify the post creation and post update Add new tests to verify the blog post access as anonymous user
Implement new tests to verify the post creation and post update Add new tests to verify the blog post access as anonymous user
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
73eeabbfdba1c1a3a4852e0d04aff501ec914e97
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016, 2018, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Html_Parser; package body Wiki.Parsers.Html is use type Wiki.Html_Parser.State_Type; use type Wiki.Html_Parser.Entity_State_Type; use type Wiki.Buffers.Buffer_Access; procedure Parse_Line_Fragment (Parser : in out Parser_Type; Text : in out Wiki.Strings.WString); procedure Parse_Line_Fragment (Parser : in out Parser_Type; Text : in out Wiki.Strings.WString) is procedure Process (Kind : in Wiki.Html_Parser.State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); procedure Process (Kind : in Wiki.Html_Parser.State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is Tag : constant Wiki.Html_Tag := Wiki.Find_Tag (Name); begin if Kind = Wiki.Html_Parser.HTML_START then Start_Element (Parser, Tag, Attributes); elsif Kind = Wiki.Html_Parser.HTML_END then End_Element (Parser, Tag); elsif Kind = Wiki.Html_Parser.HTML_START_END then Start_Element (Parser, Tag, Attributes); End_Element (Parser, Tag); end if; end Process; Pos : Natural := Text'First; Last : constant Natural := Text'Last; First : Natural := Text'First; C : Wiki.Strings.WChar; begin if not Wiki.Html_Parser.Is_Empty (Parser.Html) then Wiki.Html_Parser.Parse_Element (Parser.Html, Text, Pos, Process'Access, Pos); end if; First := Pos; while Pos <= Last loop C := Text (Pos); case C is when '<' => if First < Pos then Append (Parser.Text, Text (First .. Pos - 1)); end if; Wiki.Html_Parser.Parse_Element (Parser.Html, Text, Pos + 1, Process'Access, Pos); First := Pos; when '&' => declare Status : Wiki.Html_Parser.Entity_State_Type := Wiki.Html_Parser.ENTITY_NONE; Next : Positive; begin Wiki.Html_Parser.Parse_Entity (Parser.Html, Text, Pos + 1, Status, C, Next); if Status = Wiki.Html_Parser.ENTITY_VALID then if First < Pos then Append (Parser.Text, Text (First .. Pos - 1)); end if; Append (Parser.Text, C); First := Next; Pos := Next; else Pos := Pos + 1; end if; end; when Wiki.Helpers.CR => Text (Pos) := ' '; Pos := Pos + 1; when Wiki.Helpers.LF => if Parser.Pre_Tag_Counter = 0 then Text (Pos) := ' '; end if; Pos := Pos + 1; when others => Pos := Pos + 1; end case; end loop; if First < Pos then Append (Parser.Text, Text (First .. Last)); end if; end Parse_Line_Fragment; procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access) is Buffer : Wiki.Buffers.Buffer_Access := Text; begin while Buffer /= null loop Parse_Line_Fragment (Parser, Buffer.Content (1 .. Buffer.Last)); Buffer := Buffer.Next_Block; end loop; end Parse_Line; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016, 2018, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Html_Parser; package body Wiki.Parsers.Html is use type Wiki.Html_Parser.State_Type; use type Wiki.Html_Parser.Entity_State_Type; use type Wiki.Buffers.Buffer_Access; procedure Parse_Line_Fragment (Parser : in out Parser_Type; Text : in out Wiki.Strings.WString); procedure Parse_Line_Fragment (Parser : in out Parser_Type; Text : in out Wiki.Strings.WString) is procedure Process (Kind : in Wiki.Html_Parser.State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); procedure Process (Kind : in Wiki.Html_Parser.State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is Tag : constant Wiki.Html_Tag := Wiki.Find_Tag (Name); begin if Kind = Wiki.Html_Parser.HTML_START then Start_Element (Parser, Tag, Attributes); elsif Kind = Wiki.Html_Parser.HTML_END then End_Element (Parser, Tag); elsif Kind = Wiki.Html_Parser.HTML_START_END then Start_Element (Parser, Tag, Attributes); End_Element (Parser, Tag); end if; end Process; Pos : Natural := Text'First; Last : constant Natural := Text'Last; First : Natural := Text'First; C : Wiki.Strings.WChar; begin if not Wiki.Html_Parser.Is_Empty (Parser.Html) then Wiki.Html_Parser.Parse_Element (Parser.Html, Text, Pos, Process'Access, Pos); end if; First := Pos; while Pos <= Last loop C := Text (Pos); case C is when '<' => if First < Pos then Append (Parser.Text, Text (First .. Pos - 1)); end if; Wiki.Html_Parser.Parse_Element (Parser.Html, Text, Pos + 1, Process'Access, Pos); First := Pos; when '&' => declare Status : Wiki.Html_Parser.Entity_State_Type := Wiki.Html_Parser.ENTITY_NONE; Next : Positive; begin Wiki.Html_Parser.Parse_Entity (Parser.Html, Text, Pos + 1, Status, C, Next); if Status = Wiki.Html_Parser.ENTITY_VALID then if First < Pos then Append (Parser.Text, Text (First .. Pos - 1)); end if; Append (Parser.Text, C); First := Next; Pos := Next; else Pos := Pos + 1; end if; end; when Wiki.Helpers.LF | Wiki.Helpers.CR => if Parser.Pre_Tag_Counter = 0 then Text (Pos) := ' '; end if; Pos := Pos + 1; when others => Pos := Pos + 1; end case; end loop; if First < Pos then Append (Parser.Text, Text (First .. Last)); end if; end Parse_Line_Fragment; procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access) is Buffer : Wiki.Buffers.Buffer_Access := Text; begin while Buffer /= null loop Parse_Line_Fragment (Parser, Buffer.Content (1 .. Buffer.Last)); Buffer := Buffer.Next_Block; end loop; end Parse_Line; end Wiki.Parsers.Html;
Fix <pre> HTML blocks to keep CR in order to preserve the end of lines (LF are already preserved)
Fix <pre> HTML blocks to keep CR in order to preserve the end of lines (LF are already preserved)
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
89f59b315a0637f0aeca64f8b15fbbb69404de24
src/ado-sequences.ads
src/ado-sequences.ads
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with ADO.Sessions; with ADO.Objects; limited with ADO.Sessions.Factory; -- == Sequence Generators == -- The sequence generator is responsible for creating unique ID's -- across all database objects. -- -- Each table can be associated with a sequence generator. -- The sequence factory is shared by several sessions and the -- implementation is thread-safe. -- -- The `HiLoGenerator` implements a simple High Low sequence generator -- by using sequences that avoid to access the database. -- -- Example: -- -- F : Factory; -- Id : Identifier; -- ... -- Allocate (Manager => F, Name => "user", Id => Id); -- -- @include ado-sequences-hilo.ads package ADO.Sequences is type Session_Factory_Access is access all ADO.Sessions.Factory.Session_Factory'Class; -- ------------------------------ -- Abstract sequence generator -- ------------------------------ type Generator is abstract new Ada.Finalization.Limited_Controlled with private; type Generator_Access is access all Generator'Class; -- Get the name of the sequence. function Get_Sequence_Name (Gen : in Generator'Class) return String; -- Allocate an identifier using the generator. procedure Allocate (Gen : in out Generator; Id : in out Objects.Object_Record'Class) is abstract; -- Get a session to connect to the database. function Get_Session (Gen : in Generator) return ADO.Sessions.Master_Session'Class; type Generator_Factory is access function (Sess_Factory : in Session_Factory_Access) return Generator_Access; -- ------------------------------ -- Sequence factory -- ------------------------------ -- The sequence <b>Factory</b> allocates unique ids for new objects. -- The factory is shared by all connections to the same database. type Factory is limited private; type Factory_Access is access all Factory; -- Allocate a unique identifier for the given sequence. procedure Allocate (Manager : in out Factory; Id : in out Objects.Object_Record'Class); -- Set a generator to be used for the given sequence. procedure Set_Generator (Manager : in out Factory; Name : in String; Gen : in Generator_Access); -- Set the default factory for creating generators. -- The default factory is the HiLo generator. procedure Set_Default_Generator (Manager : in out Factory; Factory : in Generator_Factory; Sess_Factory : in Session_Factory_Access); private use Ada.Strings.Unbounded; type Generator is abstract new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; Factory : Session_Factory_Access; end record; -- Each sequence generator is accessed through a protected type -- to make sure the allocation is unique and works in multi-threaded -- environments. protected type Sequence_Generator is -- Allocate a unique identifier for the given sequence. procedure Allocate (Id : in out Objects.Object_Record'Class); procedure Set_Generator (Name : in Unbounded_String; Gen : in Generator_Access); -- Free the generator procedure Clear; private Generator : Generator_Access; end Sequence_Generator; type Sequence_Generator_Access is access all Sequence_Generator; -- Map to keep track of allocation generators for each sequence. package Sequence_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Sequence_Generator_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => "="); -- The sequence factory map is also accessed through a protected type. protected type Factory_Map is -- Get the sequence generator associated with the name. -- If there is no such generator, an entry is created by using -- the default generator. procedure Get_Generator (Name : in Unbounded_String; Gen : out Sequence_Generator_Access); -- Set the sequence generator associated with the name. procedure Set_Generator (Name : in Unbounded_String; Gen : in Sequence_Generator_Access); -- Set the default sequence generator. procedure Set_Default_Generator (Gen : in Generator_Factory; Factory : in Session_Factory_Access); -- Clear the factory map. procedure Clear; private Map : Sequence_Maps.Map; Create_Generator : Generator_Factory; Sess_Factory : Session_Factory_Access; end Factory_Map; type Factory is new Ada.Finalization.Limited_Controlled with record Map : Factory_Map; end record; overriding procedure Finalize (Manager : in out Factory); end ADO.Sequences;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with ADO.Sessions; with ADO.Objects; limited with ADO.Sessions.Factory; -- == Sequence Generators == -- The sequence generator is responsible for creating unique ID's -- across all database objects. -- -- Each table can be associated with a sequence generator. -- The sequence factory is shared by several sessions and the -- implementation is thread-safe. -- -- The `HiLoGenerator` implements a simple High Low sequence generator -- by using sequences that avoid to access the database. -- -- Example: -- -- F : Factory; -- Id : Identifier; -- ... -- Allocate (Manager => F, Name => "user", Id => Id); -- -- @include ado-sequences-hilo.ads package ADO.Sequences is -- Exception raised when the sequence generator fails to allocate an id. Allocate_Error : exception; type Session_Factory_Access is access all ADO.Sessions.Factory.Session_Factory'Class; -- ------------------------------ -- Abstract sequence generator -- ------------------------------ type Generator is abstract new Ada.Finalization.Limited_Controlled with private; type Generator_Access is access all Generator'Class; -- Get the name of the sequence. function Get_Sequence_Name (Gen : in Generator'Class) return String; -- Allocate an identifier using the generator. procedure Allocate (Gen : in out Generator; Id : in out Objects.Object_Record'Class) is abstract; -- Get a session to connect to the database. function Get_Session (Gen : in Generator) return ADO.Sessions.Master_Session'Class; type Generator_Factory is access function (Sess_Factory : in Session_Factory_Access) return Generator_Access; -- ------------------------------ -- Sequence factory -- ------------------------------ -- The sequence <b>Factory</b> allocates unique ids for new objects. -- The factory is shared by all connections to the same database. type Factory is limited private; type Factory_Access is access all Factory; -- Allocate a unique identifier for the given sequence. procedure Allocate (Manager : in out Factory; Id : in out Objects.Object_Record'Class); -- Set a generator to be used for the given sequence. procedure Set_Generator (Manager : in out Factory; Name : in String; Gen : in Generator_Access); -- Set the default factory for creating generators. -- The default factory is the HiLo generator. procedure Set_Default_Generator (Manager : in out Factory; Factory : in Generator_Factory; Sess_Factory : in Session_Factory_Access); private use Ada.Strings.Unbounded; type Generator is abstract new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; Factory : Session_Factory_Access; end record; -- Each sequence generator is accessed through a protected type -- to make sure the allocation is unique and works in multi-threaded -- environments. protected type Sequence_Generator is -- Allocate a unique identifier for the given sequence. procedure Allocate (Id : in out Objects.Object_Record'Class); procedure Set_Generator (Name : in Unbounded_String; Gen : in Generator_Access); -- Free the generator procedure Clear; private Generator : Generator_Access; end Sequence_Generator; type Sequence_Generator_Access is access all Sequence_Generator; -- Map to keep track of allocation generators for each sequence. package Sequence_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Sequence_Generator_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => "="); -- The sequence factory map is also accessed through a protected type. protected type Factory_Map is -- Get the sequence generator associated with the name. -- If there is no such generator, an entry is created by using -- the default generator. procedure Get_Generator (Name : in Unbounded_String; Gen : out Sequence_Generator_Access); -- Set the sequence generator associated with the name. procedure Set_Generator (Name : in Unbounded_String; Gen : in Sequence_Generator_Access); -- Set the default sequence generator. procedure Set_Default_Generator (Gen : in Generator_Factory; Factory : in Session_Factory_Access); -- Clear the factory map. procedure Clear; private Map : Sequence_Maps.Map; Create_Generator : Generator_Factory; Sess_Factory : Session_Factory_Access; end Factory_Map; type Factory is new Ada.Finalization.Limited_Controlled with record Map : Factory_Map; end record; overriding procedure Finalize (Manager : in out Factory); end ADO.Sequences;
Declare the Allocate_Error exception
Declare the Allocate_Error exception
Ada
apache-2.0
stcarrez/ada-ado
6bc91f37bf223392da87558a002dba4d6eae53ef
matp/src/events/mat-events-targets.ads
matp/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Ada.Finalization; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is (MSG_BEGIN, MSG_END, MSG_LIBRARY, MSG_MALLOC, MSG_FREE, MSG_REALLOC ); type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Next_Id : Event_Id_Type := 0; Prev_Id : Event_Id_Type := 0; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; Old_Size : MAT.Types.Target_Size; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type; type Event_Info_Type is record First_Event : Target_Event; Last_Event : Target_Event; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; end record; package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Id : in Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in Event_Id_Type); -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the first and last event that have been received. procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); -- Clear the events. procedure Clear; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is new Ada.Finalization.Limited_Controlled with record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; -- Release the storage allocated for the events. overriding procedure Finalize (Target : in out Target_Events); end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Ada.Finalization; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is (MSG_BEGIN, MSG_END, MSG_LIBRARY, MSG_MALLOC, MSG_FREE, MSG_REALLOC ); type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Next_Id : Event_Id_Type := 0; Prev_Id : Event_Id_Type := 0; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; Old_Size : MAT.Types.Target_Size; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type; type Event_Info_Type is record First_Event : Target_Event; Last_Event : Target_Event; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; end record; package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. -- Update the event instance to allocate the event Id. procedure Insert (Target : in out Target_Events; Event : in out Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Id : in Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in Event_Id_Type); -- Add the event in the list of events. -- Update the event instance to allocate the event Id. procedure Insert (Event : in out Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the first and last event that have been received. procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); -- Clear the events. procedure Clear; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is new Ada.Finalization.Limited_Controlled with record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; -- Release the storage allocated for the events. overriding procedure Finalize (Target : in out Target_Events); end MAT.Events.Targets;
Change the Insert procedures to update the Event.Id after the insertion
Change the Insert procedures to update the Event.Id after the insertion
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
52681a3d35f3aec0f373cf19f085efd0dbdbe877
tools/druss-commands.adb
tools/druss-commands.adb
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Util.Strings; with Util.Log.Loggers; with Readline; with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; with Druss.Commands.Devices; with Druss.Commands.Ping; package body Druss.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands"); function Uptime_Image (Value : in Natural) return String; procedure Quit (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; Device_Commands : aliased Druss.Commands.Devices.Command_Type; Ping_Commands : aliased Druss.Commands.Ping.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is pragma Unreferenced (Command); begin if Args.Get_Count < Arg_Pos then Context.Console.Notice (N_USAGE, "Missing argument for command"); Druss.Commands.Driver.Usage (Args); end if; declare procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type); Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-d] [-i] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -d Debug execution mode" & ASCII.LF & " -i Enter the interactive mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); Driver.Add_Command ("devices", Device_Commands'Access); Driver.Add_Command ("ping", Ping_Commands'Access); end Initialize; -- ------------------------------ -- Quit the interactive loop. -- ------------------------------ procedure Quit (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name, Args, Context); begin raise Stop_Interactive; end Quit; -- ------------------------------ -- Enter in the interactive main loop waiting for user commands and executing them. -- ------------------------------ procedure Interactive (Context : in out Context_Type) is Args : Util.Commands.String_Argument_List (Max_Length => 1000, Max_Args => 100); begin Log.Debug ("Entering in interactive mode"); Driver.Add_Command (Name => "quit", Handler => Quit'Access); loop declare Line : constant String := Readline.Get_Line ("druss>"); begin Log.Debug ("Execute: {0}", Line); Args.Initialize (Line); Driver.Execute (Args.Get_Command_Name, Args, Context); exception when Stop_Interactive => Log.Debug ("Leaving interactive mode"); exit; when others => Context.Console.Notice (N_INFO, "Command failed"); end; end loop; exception when Ada.IO_Exceptions.End_Error => Log.Debug ("End_Error exception received"); end Interactive; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; function Uptime_Image (Value : in Natural) return String is D : constant Natural := Value / 86400; R : constant Natural := Value mod 86400; H : constant Natural := R / 3600; M : constant Natural := (R mod 3600) / 60; S : constant Natural := (R mod 3600) mod 60; begin if D > 0 then return Util.Strings.Image (D) & "d" & (if H > 0 then Natural'Image (H) & "h" else "") & (if M > 0 then Natural'Image (M) & "m" else ""); elsif H > 0 then return Util.Strings.Image (H) & "h" & (if M > 0 then Natural'Image (M) & "m" else ""); else return Util.Strings.Image (M) & "m" & Natural'Image (S) & "s"; end if; end Uptime_Image; -- ------------------------------ -- Print a uptime. -- ------------------------------ procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "" then Console.Print_Field (Field, Value); else Console.Print_Field (Field, Uptime_Image (Natural'Value (Value))); end if; exception when others => Console.Print_Field (Field, Value); end Print_Uptime; -- ------------------------------ -- Print a performance measure in us or ms. -- ------------------------------ procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is use Commands.Consoles; begin if Value = "" then Console.Print_Field (Field, Value); elsif Value'Length <= 3 then Console.Print_Field (Field, Value & " us", J_RIGHT); elsif Value'Length <= 6 then Console.Print_Field (Field, Value (Value'First .. Value'Last - 3) & "." & Value (Value'Last - 2 .. Value'Last) & " ms", J_RIGHT); else Console.Print_Field (Field, Value (Value'First .. Value'Last - 6) & "." & Value (Value'Last - 5 .. Value'Last - 3) & " s", J_RIGHT); end if; end Print_Perf; end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Util.Strings; with Util.Log.Loggers; with Readline; with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; with Druss.Commands.Devices; with Druss.Commands.Ping; package body Druss.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands"); function Uptime_Image (Value : in Natural) return String; procedure Quit (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; Device_Commands : aliased Druss.Commands.Devices.Command_Type; Ping_Commands : aliased Druss.Commands.Ping.Command_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type) is pragma Unreferenced (Command); begin if Args.Get_Count < Arg_Pos then Context.Console.Notice (N_USAGE, "Missing argument for command"); Druss.Commands.Driver.Usage (Args, Context); end if; declare procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type); Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-d] [-i] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -d Debug execution mode" & ASCII.LF & " -i Enter the interactive mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); Driver.Add_Command ("devices", Device_Commands'Access); Driver.Add_Command ("ping", Ping_Commands'Access); end Initialize; -- ------------------------------ -- Quit the interactive loop. -- ------------------------------ procedure Quit (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name, Args, Context); begin raise Stop_Interactive; end Quit; -- ------------------------------ -- Enter in the interactive main loop waiting for user commands and executing them. -- ------------------------------ procedure Interactive (Context : in out Context_Type) is Args : Util.Commands.String_Argument_List (Max_Length => 1000, Max_Args => 100); begin Log.Debug ("Entering in interactive mode"); Driver.Add_Command (Name => "quit", Handler => Quit'Access, Description => "quit the program"); loop declare Line : constant String := Readline.Get_Line ("druss>"); begin Log.Debug ("Execute: {0}", Line); Args.Initialize (Line); Driver.Execute (Args.Get_Command_Name, Args, Context); exception when Stop_Interactive => Log.Debug ("Leaving interactive mode"); exit; when others => Context.Console.Notice (N_INFO, "Command failed"); end; end loop; exception when Ada.IO_Exceptions.End_Error => Log.Debug ("End_Error exception received"); end Interactive; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; function Uptime_Image (Value : in Natural) return String is D : constant Natural := Value / 86400; R : constant Natural := Value mod 86400; H : constant Natural := R / 3600; M : constant Natural := (R mod 3600) / 60; S : constant Natural := (R mod 3600) mod 60; begin if D > 0 then return Util.Strings.Image (D) & "d" & (if H > 0 then Natural'Image (H) & "h" else "") & (if M > 0 then Natural'Image (M) & "m" else ""); elsif H > 0 then return Util.Strings.Image (H) & "h" & (if M > 0 then Natural'Image (M) & "m" else ""); else return Util.Strings.Image (M) & "m" & Natural'Image (S) & "s"; end if; end Uptime_Image; -- ------------------------------ -- Print a uptime. -- ------------------------------ procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "" then Console.Print_Field (Field, Value); else Console.Print_Field (Field, Uptime_Image (Natural'Value (Value))); end if; exception when others => Console.Print_Field (Field, Value); end Print_Uptime; -- ------------------------------ -- Print a performance measure in us or ms. -- ------------------------------ procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is use Commands.Consoles; begin if Value = "" then Console.Print_Field (Field, Value); elsif Value'Length <= 3 then Console.Print_Field (Field, Value & " us", J_RIGHT); elsif Value'Length <= 6 then Console.Print_Field (Field, Value (Value'First .. Value'Last - 3) & "." & Value (Value'Last - 2 .. Value'Last) & " ms", J_RIGHT); else Console.Print_Field (Field, Value (Value'First .. Value'Last - 6) & "." & Value (Value'Last - 5 .. Value'Last - 3) & " s", J_RIGHT); end if; end Print_Perf; end Druss.Commands;
Update call to Add_Command to give a description\
Update call to Add_Command to give a description\
Ada
apache-2.0
stcarrez/bbox-ada-api
d0ab12f36377fddc0c022062223506a1dc863dbd
src/gen-commands-docs.ads
src/gen-commands-docs.ads
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Docs is -- ------------------------------ -- Documentation Command -- ------------------------------ -- This command extracts documentation from the project files and collect them -- together to build the project documentation. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Docs;
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Docs is -- ------------------------------ -- Documentation Command -- ------------------------------ -- This command extracts documentation from the project files and collect them -- together to build the project documentation. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Docs;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
8bb36925aaedb3152dbdc2243cc9c2938561c99e
src/security-oauth.ads
src/security-oauth.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 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.Strings.Unbounded; -- = OAuth = -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group in RFC 6749: -- The OAuth 2.0 Authorization Framework. -- -- @include security-oauth-clients.ads -- @include security-oauth-servers.ads package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents -- RFC 6749: 11.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"; -- RFC 6749: 5.2. Error Response INVALID_REQUEST : aliased constant String := "invalid_request"; INVALID_CLIENT : aliased constant String := "invalid_client"; INVALID_GRANT : aliased constant String := "invalid_grant"; UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client"; UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type"; INVALID_SCOPE : aliased constant String := "invalid_scope"; -- RFC 6749: 4.1.2.1. Error Response ACCESS_DENIED : aliased constant String := "access_denied"; UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type"; SERVER_ERROR : aliased constant String := "server_error"; TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable"; type Client_Authentication_Type is (AUTH_NONE, AUTH_BASIC); -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is tagged private; -- Get the application identifier. function Get_Application_Identifier (App : in Application) return String; -- Set the application identifier used by the OAuth authorization server -- to identify the application (for example, the App ID in Facebook). procedure Set_Application_Identifier (App : in out Application; Client : in String); -- Set the application secret defined in the OAuth authorization server -- for the application (for example, the App Secret in Facebook). procedure Set_Application_Secret (App : in out Application; Secret : in String); -- Set the redirection callback that will be used to redirect the user -- back to the application after the OAuth authorization is finished. procedure Set_Application_Callback (App : in out Application; URI : in String); -- Set the client authentication method used when doing OAuth calls for this application. -- See RFC 6749, 2.3. Client Authentication procedure Set_Client_Authentication (App : in out Application; Method : in Client_Authentication_Type); private type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; Client_Auth : Client_Authentication_Type := AUTH_NONE; end record; end Security.OAuth;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2016, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- = OAuth = -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group in RFC 6749: -- The OAuth 2.0 Authorization Framework. -- -- @include security-oauth-clients.ads -- @include security-oauth-servers.ads package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents -- RFC 6749: 11.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"; NONCE_TOKEN : constant String := "nonce"; -- RFC 6749: 5.2. Error Response INVALID_REQUEST : aliased constant String := "invalid_request"; INVALID_CLIENT : aliased constant String := "invalid_client"; INVALID_GRANT : aliased constant String := "invalid_grant"; UNAUTHORIZED_CLIENT : aliased constant String := "unauthorized_client"; UNSUPPORTED_GRANT_TYPE : aliased constant String := "unsupported_grant_type"; INVALID_SCOPE : aliased constant String := "invalid_scope"; -- RFC 6749: 4.1.2.1. Error Response ACCESS_DENIED : aliased constant String := "access_denied"; UNSUPPORTED_RESPONSE_TYPE : aliased constant String := "unsupported_response_type"; SERVER_ERROR : aliased constant String := "server_error"; TEMPORARILY_UNAVAILABLE : aliased constant String := "temporarily_unavailable"; type Client_Authentication_Type is (AUTH_NONE, AUTH_BASIC); -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is tagged private; -- Get the application identifier. function Get_Application_Identifier (App : in Application) return String; -- Set the application identifier used by the OAuth authorization server -- to identify the application (for example, the App ID in Facebook). procedure Set_Application_Identifier (App : in out Application; Client : in String); -- Set the application secret defined in the OAuth authorization server -- for the application (for example, the App Secret in Facebook). procedure Set_Application_Secret (App : in out Application; Secret : in String); -- Set the redirection callback that will be used to redirect the user -- back to the application after the OAuth authorization is finished. procedure Set_Application_Callback (App : in out Application; URI : in String); -- Set the client authentication method used when doing OAuth calls for this application. -- See RFC 6749, 2.3. Client Authentication procedure Set_Client_Authentication (App : in out Application; Method : in Client_Authentication_Type); private type Application is tagged record Client_Id : Ada.Strings.Unbounded.Unbounded_String; Secret : Ada.Strings.Unbounded.Unbounded_String; Callback : Ada.Strings.Unbounded.Unbounded_String; Client_Auth : Client_Authentication_Type := AUTH_NONE; end record; end Security.OAuth;
Declare the NONCE_TOKEN
Declare the NONCE_TOKEN
Ada
apache-2.0
stcarrez/ada-security
60bc7b618b50ad8d19b2b61f7083a1b1a1372e1d
mat/src/mat-expressions.ads
mat/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events.Targets; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_CONDITION, N_THREAD); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events.Targets; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_CONDITION, N_THREAD); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); end MAT.Expressions;
Declare the Is_Selected operation on a Node_Type
Declare the Is_Selected operation on a Node_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d2c383766493e43f6279aaf715e3474625132b57
src/natools-web-pages.adb
src/natools-web-pages.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.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.Static_Maps.Web.Pages; package body Natools.Web.Pages is type Context_Type (Site : access constant Sites.Site; Page : access constant Page_Data) is null record; procedure Append (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Data : in S_Expressions.Atom); procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Sub_Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Expression : in out S_Expressions.Lockable.Descriptor'Class; Lookup_Element : in Boolean := False; Lookup_Template : in Boolean := False); procedure Sub_Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Name : in S_Expressions.Atom; Fallback : in out S_Expressions.Lockable.Descriptor'Class; Lookup_Element : in Boolean; Lookup_Template : in Boolean) with Pre => Lookup_Element or Lookup_Template; --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); package Components renames Natools.Static_Maps.Web.Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Elements => Containers.Set_Expressions (Data.Elements, Arguments); end case; end Execute; procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Meaningless_Type, Execute); ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Data : in S_Expressions.Atom) is pragma Unreferenced (Context); begin Exchanges.Append (Exchange, Data); end Append; procedure Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; package Commands renames Natools.Static_Maps.Web.Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => null; when Commands.Element => Sub_Render (Exchange, Context, Arguments, Lookup_Element => True); when Commands.Template => Sub_Render (Exchange, Context, Arguments, Lookup_Template => True); end case; end Render; procedure Render_Page is new S_Expressions.Interpreter_Loop (Exchanges.Exchange, Context_Type, Render, Append); procedure Sub_Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Expression : in out S_Expressions.Lockable.Descriptor'Class; Lookup_Element : in Boolean := False; Lookup_Template : in Boolean := False) is use type S_Expressions.Events.Event; begin if (Lookup_Element or Lookup_Template) and then Expression.Current_Event = S_Expressions.Events.Add_Atom then declare Name : constant S_Expressions.Atom := Expression.Current_Atom; begin Expression.Next; Sub_Render (Exchange, Context, Name, Expression, Lookup_Element, Lookup_Template); end; else Render_Page (Expression, Exchange, Context); end if; end Sub_Render; procedure Sub_Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Name : in S_Expressions.Atom; Fallback : in out S_Expressions.Lockable.Descriptor'Class; Lookup_Element : in Boolean; Lookup_Template : in Boolean) is Template : S_Expressions.Caches.Cursor; Found : Boolean; begin if Lookup_Element then Context.Page.Get_Element (Name, Template, Found); if Found then Render_Page (Template, Exchange, Context); return; end if; end if; if Lookup_Template then Sites.Get_Template (Context.Site.all, Name, Template, Found); if Found then Render_Page (Template, Exchange, Context); return; end if; end if; case Fallback.Current_Event is when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => Log (Severities.Error, "Page expression """ & S_Expressions.To_String (Name) & """ not found"); return; when S_Expressions.Events.Open_List | S_Expressions.Events.Add_Atom => Render_Page (Fallback, Exchange, Context); end case; end Sub_Render; ------------------------- -- Page_Data Interface -- ------------------------- procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ---------------------- -- Public Interface -- ---------------------- function Create (File_Path, Web_Path : in S_Expressions.Atom) return Page_Ref is function Create_Page return Page_Data; function Create_Page return Page_Data is Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path)); begin return Result : Page_Data := (File_Path => S_Expressions.Atom_Ref_Constructors.Create (File_Path), Web_Path => S_Expressions.Atom_Ref_Constructors.Create (Web_Path), Elements => <>) do Read_Page (Reader, Result, Meaningless_Value); end return; end Create_Page; begin return (Ref => Data_Refs.Create (Create_Page'Access)); end Create; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Exchanges.Exchange; Parent : aliased in Sites.Site; Extra_Path : in S_Expressions.Atom) is begin if Extra_Path'Length > 0 then return; end if; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Null_Expression : S_Expressions.Caches.Cursor; begin Sub_Render (Exchange, (Parent'Access, Accessor.Data), Sites.Default_Template (Parent), Null_Expression, Lookup_Element => True, Lookup_Template => True); end; end Respond; end Natools.Web.Pages;
------------------------------------------------------------------------------ -- 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.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.Static_Maps.Web.Pages; with Natools.Web.Error_Pages; package body Natools.Web.Pages is type Context_Type (Site : access constant Sites.Site; Page : access constant Page_Data) is null record; procedure Append (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Data : in S_Expressions.Atom); procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Sub_Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Expression : in out S_Expressions.Lockable.Descriptor'Class; Lookup_Element : in Boolean := False; Lookup_Template : in Boolean := False); procedure Sub_Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Name : in S_Expressions.Atom; Fallback : in out S_Expressions.Lockable.Descriptor'Class; Lookup_Element : in Boolean; Lookup_Template : in Boolean) with Pre => Lookup_Element or Lookup_Template; --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); package Components renames Natools.Static_Maps.Web.Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Elements => Containers.Set_Expressions (Data.Elements, Arguments); end case; end Execute; procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Meaningless_Type, Execute); ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Data : in S_Expressions.Atom) is pragma Unreferenced (Context); begin Exchanges.Append (Exchange, Data); end Append; procedure Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; package Commands renames Natools.Static_Maps.Web.Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => null; when Commands.Element => Sub_Render (Exchange, Context, Arguments, Lookup_Element => True); when Commands.Template => Sub_Render (Exchange, Context, Arguments, Lookup_Template => True); end case; end Render; procedure Render_Page is new S_Expressions.Interpreter_Loop (Exchanges.Exchange, Context_Type, Render, Append); procedure Sub_Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Expression : in out S_Expressions.Lockable.Descriptor'Class; Lookup_Element : in Boolean := False; Lookup_Template : in Boolean := False) is use type S_Expressions.Events.Event; begin if (Lookup_Element or Lookup_Template) and then Expression.Current_Event = S_Expressions.Events.Add_Atom then declare Name : constant S_Expressions.Atom := Expression.Current_Atom; begin Expression.Next; Sub_Render (Exchange, Context, Name, Expression, Lookup_Element, Lookup_Template); end; else Render_Page (Expression, Exchange, Context); end if; end Sub_Render; procedure Sub_Render (Exchange : in out Exchanges.Exchange; Context : in Context_Type; Name : in S_Expressions.Atom; Fallback : in out S_Expressions.Lockable.Descriptor'Class; Lookup_Element : in Boolean; Lookup_Template : in Boolean) is Template : S_Expressions.Caches.Cursor; Found : Boolean; begin if Lookup_Element then Context.Page.Get_Element (Name, Template, Found); if Found then Render_Page (Template, Exchange, Context); return; end if; end if; if Lookup_Template then Sites.Get_Template (Context.Site.all, Name, Template, Found); if Found then Render_Page (Template, Exchange, Context); return; end if; end if; case Fallback.Current_Event is when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => Log (Severities.Error, "Page expression """ & S_Expressions.To_String (Name) & """ not found"); return; when S_Expressions.Events.Open_List | S_Expressions.Events.Add_Atom => Render_Page (Fallback, Exchange, Context); end case; end Sub_Render; ------------------------- -- Page_Data Interface -- ------------------------- procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ---------------------- -- Public Interface -- ---------------------- function Create (File_Path, Web_Path : in S_Expressions.Atom) return Page_Ref is function Create_Page return Page_Data; function Create_Page return Page_Data is Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path)); begin return Result : Page_Data := (File_Path => S_Expressions.Atom_Ref_Constructors.Create (File_Path), Web_Path => S_Expressions.Atom_Ref_Constructors.Create (Web_Path), Elements => <>) do Read_Page (Reader, Result, Meaningless_Value); end return; end Create_Page; begin return (Ref => Data_Refs.Create (Create_Page'Access)); end Create; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Exchanges.Exchange; Parent : aliased in Sites.Site; Extra_Path : in S_Expressions.Atom) is begin if Extra_Path'Length > 0 then return; end if; Check_Method : declare use Exchanges; Allowed : Boolean; begin Error_Pages.Check_Method (Exchange, Parent, (GET, HEAD), Allowed); if not Allowed then return; end if; end Check_Method; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Null_Expression : S_Expressions.Caches.Cursor; begin Sub_Render (Exchange, (Parent'Access, Accessor.Data), Sites.Default_Template (Parent), Null_Expression, Lookup_Element => True, Lookup_Template => True); end; end Respond; end Natools.Web.Pages;
test the request method and return Method Not Allowed when appropriate
pages: test the request method and return Method Not Allowed when appropriate
Ada
isc
faelys/natools-web,faelys/natools-web
5ccc4d75a7373a78089cdfd6b74e25f20213762f
matp/src/mat-readers-streams.ads
matp/src/mat-readers-streams.ads
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- 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.Streams.Buffered; with MAT.Events.Probes; package MAT.Readers.Streams is type Stream_Reader_Type is new MAT.Events.Probes.Probe_Manager_Type with private; -- Read the events from the stream and stop when the end of the stream is reached. procedure Read_All (Reader : in out Stream_Reader_Type); -- Read a message from the stream. overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message_Type); private type Stream_Reader_Type is new MAT.Events.Probes.Probe_Manager_Type with record Stream : Util.Streams.Buffered.Buffered_Stream; Data : Util.Streams.Buffered.Buffer_Access; end record; end MAT.Readers.Streams;
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams.Buffered; with MAT.Events.Probes; package MAT.Readers.Streams is type Stream_Reader_Type is new MAT.Events.Probes.Probe_Manager_Type with private; -- Read the events from the stream and stop when the end of the stream is reached. procedure Read_All (Reader : in out Stream_Reader_Type); -- Read a message from the stream. overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message_Type); private type Stream_Reader_Type is new MAT.Events.Probes.Probe_Manager_Type with record Stream : Util.Streams.Buffered.Input_Buffer_Stream; Data : Util.Streams.Buffered.Buffer_Access; end record; end MAT.Readers.Streams;
Rename Buffered_Stream type into Input_Buffer_Stream
Rename Buffered_Stream type into Input_Buffer_Stream
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
858285b678386f1d3c00738bf8ac40ad311b2f19
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; -- ------------------------------ -- 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;
----------------------------------------------------------------------- -- 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; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission'Class) 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 Has_Permission function
Implement the Has_Permission function
Ada
apache-2.0
stcarrez/ada-security
54dbbf50147a074d80e90b41b706cfbba60b9fb4
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Log.Loggers; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Permission Manager -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is begin null; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); -- package Role_Config is -- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); -- pragma Warnings (Off, Role_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Parse (File); end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is begin null; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Log.Loggers; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); -- package Role_Config is -- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); -- pragma Warnings (Off, Role_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Parse (File); end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is begin null; end Finalize; end Security.Policies;
Implement Add_Policy
Implement Add_Policy
Ada
apache-2.0
stcarrez/ada-security
11117bc583646def908b24a7c71bfc08714ac02b
src/util-encoders-aes.ads
src/util-encoders-aes.ads
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Interfaces; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); private use Interfaces; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key; Rounds : Natural := 0; end record; type Encoder is new Util.Encoders.Transformer with record Key : Key_Type; Mode : AES_Mode := CBC; end record; end Util.Encoders.AES;
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Interfaces; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32; procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset); -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); private use Interfaces; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key; Rounds : Natural := 0; end record; type Encoder is new Util.Encoders.Transformer with record IV : Word_Block_Type; Key : Key_Type; Mode : AES_Mode := CBC; end record; end Util.Encoders.AES;
Declare Encrypt and Finish procedures
Declare Encrypt and Finish procedures
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1e0a49ff65f9a8d3011272e84530fe56228fa446
awa/src/aws/awa-mail-clients-aws_smtp.adb
awa/src/aws/awa-mail-clients-aws_smtp.adb
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email to {0}", ""); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); else Log.Info ("Disable send email to {0}", ""); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Self := Result; Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server, Port => Positive'Value (Port)); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in String) is begin Message.Content := To_Unbounded_String (Content); end Set_Body; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email to {0}", ""); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Message => To_String (Message.Content), Status => Result); else Log.Info ("Disable send email to {0}", ""); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Self := Result; Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Server := AWS.SMTP.Client.Initialize (Server_Name => Server, Port => Positive'Value (Port)); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
Fix compilation warning, ignore Kind parameter
Fix compilation warning, ignore Kind parameter
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
6d184672156754f1a7602bcd51ef9901e93c4530
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with AWA.Tests; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space", Test_Create_Wiki_Space'Access); end Add_Tests; -- Test creation of a wiki space. procedure Test_Create_Wiki_Space (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; T.Assert (T.Manager /= null, "There is no wiki manager"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Assert (W.Is_Inserted, "The new wiki space was not created"); end Test_Create_Wiki_Space; end AWA.Wikis.Modules.Tests;
----------------------------------------------------------------------- -- awa-wikis-modules-tests -- Unit tests for wikis service -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with AWA.Tests; with AWA.Tests.Helpers; with AWA.Tests.Helpers.Users; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Wikis.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space", Test_Create_Wiki_Space'Access); end Add_Tests; -- ------------------------------ -- Test creation of a wiki space. -- ------------------------------ procedure Test_Create_Wiki_Space (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; W : AWA.Wikis.Models.Wiki_Space_Ref; W2 : AWA.Wikis.Models.Wiki_Space_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Wikis.Modules.Get_Wiki_Module; T.Assert (T.Manager /= null, "There is no wiki manager"); W.Set_Name ("Test wiki space"); T.Manager.Create_Wiki_Space (W); T.Assert (W.Is_Inserted, "The new wiki space was not created"); W.Set_Name ("Test wiki space update"); W.Set_Is_Public (True); T.Manager.Save_Wiki_Space (W); T.Manager.Load_Wiki_Space (Wiki => W2, Id => W.Get_Id); Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name), "Invalid wiki space name"); end Test_Create_Wiki_Space; end AWA.Wikis.Modules.Tests;
Update the wiki space create unit test
Update the wiki space create unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a0066a51dde3fd7b7a5e8d27e0e1abd8035c3c9d
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return False; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; 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; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the 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; -- ------------------------------ -- 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; end MAT.Expressions;
Implement the Parse function
Implement the Parse function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f4282b933e178b573428649eec4ffc55b80319db
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Is_Hidden : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; -- === Wiki Parsers === -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt> -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- <tt>Set_Syntax</tt> procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki <tt>Document</tt> is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream -- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure -- completes, the <tt>Document</tt> instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MIX); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Parser_Handler is access procedure (P : in out Parser; Token : in Wiki.Strings.WChar); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access constant Parser_Table; type Parser is tagged limited record Context : Wiki.Plugins.Plugin_Context; Pending : Wiki.Strings.WChar; Has_Pending : Boolean; Previous_Syntax : Wiki_Syntax; Table : Parser_Table_Access; Document : Wiki.Documents.Document; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Is_Hidden : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; end record; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wiki.Strings.WChar); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wiki.Strings.WChar); -- Skip all the spaces and tabs as well as end of the current line (CR+LF). procedure Skip_End_Of_Line (P : in out Parser); -- Skip white spaces and tabs. procedure Skip_Spaces (P : in out Parser); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); -- Append a character to the wiki text buffer. procedure Parse_Text (P : in out Parser; Token : in Wiki.Strings.WChar); -- Check if the link refers to an image and must be rendered as an image. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; -- Extract a list of parameters separated by the given separator (ex: '|'). procedure Parse_Parameters (P : in out Parser; Separator : in Wiki.Strings.WChar; Terminator : in Wiki.Strings.WChar; Names : in String_Array; Max : in Positive := 200); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Parse_Token (P : in out Parser); end Wiki.Parsers;
Add a Max parameter to the Parse_Parameters procedure
Add a Max parameter to the Parse_Parameters procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
25dfaa280ee693589c725192e56a4e6593d6b2e2
awa/plugins/awa-mail/src/awa-mail-clients-files.ads
awa/plugins/awa-mail/src/awa-mail-clients-files.ads
----------------------------------------------------------------------- -- awa-mail-clients-files -- Mail client dump/file implementation -- 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.Properties; with Util.Concurrent.Counters; -- The <b>AWA.Mail.Clients.Files</b> package provides a dump implementation of the -- mail client interfaces on top of raw system files. package AWA.Mail.Clients.Files is NAME : constant String := "file"; -- ------------------------------ -- Mail Message -- ------------------------------ -- The <b>File_Mail_Message</b> represents a mail message that is written on a file in -- in specific directory. type File_Mail_Message is new Mail_Message with private; type File_Mail_Message_Access is access all File_Mail_Message'Class; -- Set the <tt>From</tt> part of the message. overriding procedure Set_From (Message : in out File_Mail_Message; Name : in String; Address : in String); -- Add a recipient for the message. overriding procedure Add_Recipient (Message : in out File_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String); -- Set the subject of the message. overriding procedure Set_Subject (Message : in out File_Mail_Message; Subject : in String); -- Set the body of the message. overriding procedure Set_Body (Message : in out File_Mail_Message; Content : in String); -- Send the email message. overriding procedure Send (Message : in out File_Mail_Message); -- ------------------------------ -- Mail Manager -- ------------------------------ -- The <b>Mail_Manager</b> is the entry point to create a new mail message -- and be able to send it. type File_Mail_Manager is new Mail_Manager with private; type File_Mail_Manager_Access is access all File_Mail_Manager'Class; -- Create a file based mail manager and configure it according to the properties. function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access; -- Create a new mail message. overriding function Create_Message (Manager : in File_Mail_Manager) return Mail_Message_Access; private type File_Mail_Message is new Mail_Message with record Manager : File_Mail_Manager_Access; From : Ada.Strings.Unbounded.Unbounded_String; To : Ada.Strings.Unbounded.Unbounded_String; Cc : Ada.Strings.Unbounded.Unbounded_String; Bcc : Ada.Strings.Unbounded.Unbounded_String; Subject : Ada.Strings.Unbounded.Unbounded_String; Message : Ada.Strings.Unbounded.Unbounded_String; end record; type File_Mail_Manager is new Mail_Manager with record Self : File_Mail_Manager_Access; Path : Ada.Strings.Unbounded.Unbounded_String; Index : Util.Concurrent.Counters.Counter; end record; end AWA.Mail.Clients.Files;
----------------------------------------------------------------------- -- awa-mail-clients-files -- Mail client dump/file implementation -- Copyright (C) 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 Ada.Strings.Unbounded; with Util.Properties; with Util.Concurrent.Counters; -- The <b>AWA.Mail.Clients.Files</b> package provides a dump implementation of the -- mail client interfaces on top of raw system files. package AWA.Mail.Clients.Files is NAME : constant String := "file"; -- ------------------------------ -- Mail Message -- ------------------------------ -- The <b>File_Mail_Message</b> represents a mail message that is written on a file in -- in specific directory. type File_Mail_Message is new Mail_Message with private; type File_Mail_Message_Access is access all File_Mail_Message'Class; -- Set the <tt>From</tt> part of the message. overriding procedure Set_From (Message : in out File_Mail_Message; Name : in String; Address : in String); -- Add a recipient for the message. overriding procedure Add_Recipient (Message : in out File_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String); -- Set the subject of the message. overriding procedure Set_Subject (Message : in out File_Mail_Message; Subject : in String); -- Set the body of the message. overriding procedure Set_Body (Message : in out File_Mail_Message; Content : in String); -- Send the email message. overriding procedure Send (Message : in out File_Mail_Message); -- ------------------------------ -- Mail Manager -- ------------------------------ -- The <b>Mail_Manager</b> is the entry point to create a new mail message -- and be able to send it. type File_Mail_Manager is limited new Mail_Manager with private; type File_Mail_Manager_Access is access all File_Mail_Manager'Class; -- Create a file based mail manager and configure it according to the properties. function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access; -- Create a new mail message. overriding function Create_Message (Manager : in File_Mail_Manager) return Mail_Message_Access; private type File_Mail_Message is new Mail_Message with record Manager : File_Mail_Manager_Access; From : Ada.Strings.Unbounded.Unbounded_String; To : Ada.Strings.Unbounded.Unbounded_String; Cc : Ada.Strings.Unbounded.Unbounded_String; Bcc : Ada.Strings.Unbounded.Unbounded_String; Subject : Ada.Strings.Unbounded.Unbounded_String; Message : Ada.Strings.Unbounded.Unbounded_String; end record; type File_Mail_Manager is limited new Mail_Manager with record Self : File_Mail_Manager_Access; Path : Ada.Strings.Unbounded.Unbounded_String; Index : Util.Concurrent.Counters.Counter; end record; end AWA.Mail.Clients.Files;
Make the File_Mail_Manager type a limited type
Make the File_Mail_Manager type a limited type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
598452c4a6a2256182a8536c838f4a10e409ad81
src/sys/os-windows/util-systems-os.adb
src/sys/os-windows/util-systems-os.adb
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 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.Characters.Conversions; package body Util.Systems.Os is use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; use type Interfaces.C.size_t; function To_WSTR (Value : in String) return Wchar_Ptr is Result : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Value'Length + 1); Pos : Interfaces.C.size_t := 0; begin for C of Value loop Result (Pos) := Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (C)); Pos := Pos + 1; end loop; Result (Pos) := Interfaces.C.wide_nul; return Result; end To_WSTR; function Sys_SetFilePointerEx (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Result : access Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return BOOL with Import => True, Convention => Stdcall, Link_Name => "SetFilePointerEx"; 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 is Result : aliased Util.Systems.Types.off_t; begin if Sys_SetFilePointerEx (Fs, Offset, Result'Access, Mode) /= 0 then return Result; else return -1; end if; end Sys_Lseek; function Sys_GetFileSizeEx (Fs : in File_Type; Result : access Util.Systems.Types.off_t) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetFileSizeEx"; function Sys_GetFileTime (Fs : in File_Type; Create : access FileTime; AccessTime : access FileTime; ModifyTime : access FileTime) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetFileTime"; TICKS_PER_SECOND : constant := 10000000; EPOCH_DIFFERENCE : constant := 11644473600; function To_Time (Time : in FileTime) return Types.Time_Type is Value : Interfaces.Unsigned_64; begin Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time.dwHighDateTime), 32); Value := Value + Interfaces.Unsigned_64 (Time.dwLowDateTime); Value := Value / TICKS_PER_SECOND; Value := Value - EPOCH_DIFFERENCE; return Types.Time_Type (Value); end To_Time; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer is Size : aliased Util.Systems.Types.off_t; Creation_Time : aliased FileTime; Access_Time : aliased FileTime; Write_Time : aliased FileTime; begin Stat.st_dev := 0; Stat.st_ino := 0; Stat.st_mode := 0; Stat.st_nlink := 0; Stat.st_uid := 0; Stat.st_gid := 0; Stat.st_rdev := 0; Stat.st_atime := 0; Stat.st_mtime := 0; Stat.st_ctime := 0; if Sys_GetFileSizeEx (Fs, Size'Access) = 0 then return -1; end if; if Sys_GetFileTime (Fs, Creation_Time'Access, Access_Time'Access, Write_Time'Access) = 0 then return -1; end if; Stat.st_size := Size; Stat.st_ctime := To_Time (Creation_Time); Stat.st_mtime := To_Time (Write_Time); Stat.st_atime := To_Time (Access_Time); return 0; end Sys_Fstat; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type is pragma Unreferenced (Mode); function Has_Flag (M : in Interfaces.C.int; F : in Interfaces.C.int) return Boolean is ((Interfaces.Unsigned_32 (M) and Interfaces.Unsigned_32 (F)) /= 0); Sec : aliased Security_Attributes; Result : File_Type; Desired_Access : DWORD; Share_Mode : DWORD := FILE_SHARE_READ + FILE_SHARE_WRITE; Creation : DWORD; WPath : Wchar_Ptr; begin WPath := To_WSTR (Interfaces.C.Strings.Value (Path)); Sec.Length := Security_Attributes'Size / 8; Sec.Security_Descriptor := System.Null_Address; Sec.Inherit := True; if Has_Flag (Flags, O_WRONLY) then Desired_Access := GENERIC_WRITE; elsif Has_Flag (Flags, O_RDWR) then Desired_Access := GENERIC_READ + GENERIC_WRITE; else Desired_Access := GENERIC_READ; end if; if Has_Flag (Flags, O_CREAT) then if Has_Flag (Flags, O_EXCL) then Creation := CREATE_NEW; else Creation := CREATE_ALWAYS; end if; else Creation := OPEN_EXISTING; end if; if Has_Flag (Flags, O_APPEND) then Desired_Access := FILE_APPEND_DATA; end if; if Has_Flag (Flags, O_EXCL) then Share_Mode := 0; end if; Result := Create_File (WPath.all'Address, Desired_Access, Share_Mode, Sec'Unchecked_Access, Creation, FILE_ATTRIBUTE_NORMAL, NO_FILE); Free (WPath); return Result; end Sys_Open; function Sys_SetEndOfFile (Fs : in File_Type) return BOOL with Import => True, Convention => Stdcall, Link_Name => "SetEndOfFile"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer is begin if Sys_Lseek (Fs, Length, Util.Systems.Types.SEEK_SET) < 0 then return -1; end if; if Sys_SetEndOfFile (Fs) = 0 then return -1; end if; return 0; end Sys_Ftruncate; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer is pragma Unreferenced (Fd, Mode); begin return 0; end Sys_Fchmod; -- Close a file function Sys_Close (Fd : in File_Type) return Integer is begin if Close_Handle (Fd) = 0 then return -1; else return 0; end if; end Sys_Close; end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 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.Characters.Conversions; package body Util.Systems.Os is use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; use type Interfaces.C.size_t; function To_WSTR (Value : in String) return Wchar_Ptr is Result : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Value'Length + 1); Pos : Interfaces.C.size_t := 0; begin for C of Value loop Result (Pos) := Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (C)); Pos := Pos + 1; end loop; Result (Pos) := Interfaces.C.wide_nul; return Result; end To_WSTR; function Sys_SetFilePointerEx (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Result : access Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return BOOL with Import => True, Convention => Stdcall, Link_Name => "SetFilePointerEx"; 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 is Result : aliased Util.Systems.Types.off_t; begin if Sys_SetFilePointerEx (Fs, Offset, Result'Access, Mode) /= 0 then return Result; else return -1; end if; end Sys_Lseek; function Sys_GetFileSizeEx (Fs : in File_Type; Result : access Util.Systems.Types.off_t) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetFileSizeEx"; function Sys_GetFileTime (Fs : in File_Type; Create : access FileTime; AccessTime : access FileTime; ModifyTime : access FileTime) return BOOL with Import => True, Convention => Stdcall, Link_Name => "GetFileTime"; TICKS_PER_SECOND : constant := 10000000; EPOCH_DIFFERENCE : constant := 11644473600; function To_Time (Time : in FileTime) return Types.Time_Type is Value : Interfaces.Unsigned_64; begin Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time.dwHighDateTime), 32); Value := Value + Interfaces.Unsigned_64 (Time.dwLowDateTime); Value := Value / TICKS_PER_SECOND; Value := Value - EPOCH_DIFFERENCE; return Types.Time_Type (Value); end To_Time; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer is Size : aliased Util.Systems.Types.off_t; Creation_Time : aliased FileTime; Access_Time : aliased FileTime; Write_Time : aliased FileTime; begin Stat.st_dev := 0; Stat.st_ino := 0; Stat.st_mode := 0; Stat.st_nlink := 0; Stat.st_uid := 0; Stat.st_gid := 0; Stat.st_rdev := 0; Stat.st_atime := 0; Stat.st_mtime := 0; Stat.st_ctime := 0; if Sys_GetFileSizeEx (Fs, Size'Access) = 0 then return -1; end if; if Sys_GetFileTime (Fs, Creation_Time'Access, Access_Time'Access, Write_Time'Access) = 0 then return -1; end if; Stat.st_size := Size; Stat.st_ctime := To_Time (Creation_Time); Stat.st_mtime := To_Time (Write_Time); Stat.st_atime := To_Time (Access_Time); return 0; end Sys_Fstat; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type is pragma Unreferenced (Mode); function Has_Flag (M : in Interfaces.C.int; F : in Interfaces.C.int) return Boolean is ((Interfaces.Unsigned_32 (M) and Interfaces.Unsigned_32 (F)) /= 0); Sec : aliased Security_Attributes; Result : File_Type; Desired_Access : DWORD; Share_Mode : DWORD := FILE_SHARE_READ + FILE_SHARE_WRITE; Creation : DWORD; WPath : Wchar_Ptr; begin WPath := To_WSTR (Interfaces.C.Strings.Value (Path)); Sec.Length := Security_Attributes'Size / 8; Sec.Security_Descriptor := System.Null_Address; Sec.Inherit := True; if Has_Flag (Flags, O_WRONLY) then Desired_Access := GENERIC_WRITE; elsif Has_Flag (Flags, O_RDWR) then Desired_Access := GENERIC_READ + GENERIC_WRITE; else Desired_Access := GENERIC_READ; end if; if Has_Flag (Flags, O_CREAT) then if Has_Flag (Flags, O_EXCL) then Creation := CREATE_NEW; else Creation := CREATE_ALWAYS; end if; else Creation := OPEN_EXISTING; end if; if Has_Flag (Flags, O_APPEND) then Desired_Access := FILE_APPEND_DATA; end if; if Has_Flag (Flags, O_EXCL) then Share_Mode := 0; end if; Result := Create_File (WPath.all'Address, Desired_Access, Share_Mode, Sec'Unchecked_Access, Creation, FILE_ATTRIBUTE_NORMAL, NO_FILE); Free (WPath); return (if Result = INVALID_HANDLE_VALUE then NO_FILE else Result); end Sys_Open; function Sys_SetEndOfFile (Fs : in File_Type) return BOOL with Import => True, Convention => Stdcall, Link_Name => "SetEndOfFile"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer is begin if Sys_Lseek (Fs, Length, Util.Systems.Types.SEEK_SET) < 0 then return -1; end if; if Sys_SetEndOfFile (Fs) = 0 then return -1; end if; return 0; end Sys_Ftruncate; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer is pragma Unreferenced (Fd, Mode); begin return 0; end Sys_Fchmod; -- Close a file function Sys_Close (Fd : in File_Type) return Integer is begin if Close_Handle (Fd) = 0 then return -1; else return 0; end if; end Sys_Close; end Util.Systems.Os;
Fix Sys_Open to return NO_FILE if we fail to open/create the file
Fix Sys_Open to return NO_FILE if we fail to open/create the file
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c9e04dafe0fab7ddf21287d415d21ec76be4d85e
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Votes.Modules; with AWA.Tests.Helpers.Users; package body AWA.Votes.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Votes.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Votes.Services.Vote_Up", Test_Vote_Up'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Vote_Up (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : Vote_Module_Access := Get_Vote_Module; User : AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total); end; end Test_Vote_Up; end AWA.Votes.Modules.Tests;
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Votes.Modules; with AWA.Tests.Helpers.Users; package body AWA.Votes.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Votes.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For", Test_Vote_Up'Access); Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For (Undo)", Test_Vote_Undo'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Vote_Up (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : Vote_Module_Access := Get_Vote_Module; User : AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total); end; end Test_Vote_Up; -- ------------------------------ -- Test vote. -- ------------------------------ procedure Test_Vote_Undo (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : Vote_Module_Access := Get_Vote_Module; User : AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 0, Total); end; end Test_Vote_Undo; end AWA.Votes.Modules.Tests;
Add unit test for undo vote
Add unit test for undo vote
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3aa66313e087072601dba95567dcbfbb46484bcc
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, 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;
----------------------------------------------------------------------- -- 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 begin if File.Get_Original.Is_Null then declare 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; end if; 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;
Create the Image database instance and scheduler the image thumbnail job only for files that don't have any thumbnail yet
Create the Image database instance and scheduler the image thumbnail job only for files that don't have any thumbnail yet
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
61909a0a01fce372a8dcd9b307b5943e73763022
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.adb
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.adb
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012, 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in AWS.SMTP.Recipients) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is pragma Unreferenced (Kind); begin if Message.To = null then Message.To := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1); begin To (Message.To'Range) := Message.To.all; Free (Message.To); Message.To := To; end; end if; Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Alternative : in Unbounded_String; Content_Type : in String) is begin if Length (Alternative) = 0 then AWS.Attachments.Add (Message.Attachments, "", AWS.Attachments.Value (To_String (Content))); else declare Parts : AWS.Attachments.Alternatives; begin AWS.Attachments.Add (Parts, AWS.Attachments.Value (To_String (Content), Content_Type => Content_Type)); AWS.Attachments.Add (Parts, AWS.Attachments.Value (To_String (Alternative), Content_Type => "text/plain")); AWS.Attachments.Add (Message.Attachments, Parts); end; end if; end Set_Body; -- ------------------------------ -- Add an attachment with the given content. -- ------------------------------ overriding procedure Add_Attachment (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Content_Id : in String; Content_Type : in String) is Data : constant AWS.Attachments.Content := AWS.Attachments.Value (Data => To_String (Content), Content_Id => Content_Id, Content_Type => Content_Type); begin AWS.Attachments.Add (Attachments => Message.Attachments, Name => Content_Id, Data => Data); end Add_Attachment; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in AWS.SMTP.Recipients) return String is Result : Unbounded_String; begin for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if Message.To = null then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => Message.To.all, Subject => To_String (Message.Subject), Attachments => Message.Attachments, Status => Result); if not AWS.SMTP.Is_Ok (Result) then Log.Error ("Cannot send email: {0}", AWS.SMTP.Status_Message (Result)); end if; else Log.Info ("Disable send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To.all)); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To); end Finalize; procedure Initialize (Client : in out AWS_Mail_Manager'Class; Props : in Util.Properties.Manager'Class) is separate; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Port := Positive'Value (Port); Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Self := Result; Initialize (Result.all, Props); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
----------------------------------------------------------------------- -- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client -- Copyright (C) 2012, 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWS.SMTP.Client; with Util.Log.Loggers; package body AWA.Mail.Clients.AWS_SMTP is use AWS.SMTP; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP"); procedure Free is new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients, Name => Recipients_Access); -- Get a printable representation of the email recipients. function Image (Recipients : in Recipients_Access) return String; -- ------------------------------ -- Set the <tt>From</tt> part of the message. -- ------------------------------ overriding procedure Set_From (Message : in out AWS_Mail_Message; Name : in String; Address : in String) is begin Message.From := AWS.SMTP.E_Mail (Name => Name, Address => Address); end Set_From; -- ------------------------------ -- Add a recipient for the message. -- ------------------------------ overriding procedure Add_Recipient (Message : in out AWS_Mail_Message; Kind : in Recipient_Type; Name : in String; Address : in String) is List : Recipients_Access := Message.To (Kind); begin if List = null then List := new AWS.SMTP.Recipients (1 .. 1); else declare To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. List'Last + 1); begin List (List'Range) := List.all; Free (List); List := To; end; end if; List (List'Last) := AWS.SMTP.E_Mail (Name => Name, Address => Address); Message.To (Kind) := List; end Add_Recipient; -- ------------------------------ -- Set the subject of the message. -- ------------------------------ overriding procedure Set_Subject (Message : in out AWS_Mail_Message; Subject : in String) is begin Message.Subject := To_Unbounded_String (Subject); end Set_Subject; -- ------------------------------ -- Set the body of the message. -- ------------------------------ overriding procedure Set_Body (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Alternative : in Unbounded_String; Content_Type : in String) is begin if Length (Alternative) = 0 then AWS.Attachments.Add (Message.Attachments, "", AWS.Attachments.Value (To_String (Content))); else declare Parts : AWS.Attachments.Alternatives; begin AWS.Attachments.Add (Parts, AWS.Attachments.Value (To_String (Content), Content_Type => Content_Type)); AWS.Attachments.Add (Parts, AWS.Attachments.Value (To_String (Alternative), Content_Type => "text/plain; charset=UTF-8")); AWS.Attachments.Add (Message.Attachments, Parts); end; end if; end Set_Body; -- ------------------------------ -- Add an attachment with the given content. -- ------------------------------ overriding procedure Add_Attachment (Message : in out AWS_Mail_Message; Content : in Unbounded_String; Content_Id : in String; Content_Type : in String) is Data : constant AWS.Attachments.Content := AWS.Attachments.Value (Data => To_String (Content), Content_Id => Content_Id, Content_Type => Content_Type); begin AWS.Attachments.Add (Attachments => Message.Attachments, Name => Content_Id, Data => Data); end Add_Attachment; -- ------------------------------ -- Get a printable representation of the email recipients. -- ------------------------------ function Image (Recipients : in Recipients_Access) return String is Result : Unbounded_String; begin if Recipients /= null then for I in Recipients'Range loop Append (Result, AWS.SMTP.Image (Recipients (I))); end loop; end if; return To_String (Result); end Image; -- ------------------------------ -- Send the email message. -- ------------------------------ overriding procedure Send (Message : in out AWS_Mail_Message) is Result : AWS.SMTP.Status; begin if (for all Recipient of Message.To => Recipient = null) then return; end if; if Message.Manager.Enable then Log.Info ("Send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To (Clients.TO))); AWS.SMTP.Client.Send (Server => Message.Manager.Server, From => Message.From, To => (if Message.To (Clients.TO) /= null then Message.To (Clients.TO).all else No_Recipient), CC => (if Message.To (Clients.CC) /= null then Message.To (Clients.CC).all else No_Recipient), BCC => (if Message.To (Clients.BCC) /= null then Message.To (Clients.BCC).all else No_Recipient), Subject => To_String (Message.Subject), Attachments => Message.Attachments, Status => Result); if not AWS.SMTP.Is_Ok (Result) then Log.Error ("Cannot send email: {0}", AWS.SMTP.Status_Message (Result)); end if; else Log.Info ("Disable send email from {0} to {1}", AWS.SMTP.Image (Message.From), Image (Message.To (Clients.TO))); end if; end Send; -- ------------------------------ -- Deletes the mail message. -- ------------------------------ overriding procedure Finalize (Message : in out AWS_Mail_Message) is begin Log.Info ("Finalize mail message"); Free (Message.To (AWA.Mail.Clients.TO)); Free (Message.To (AWA.Mail.Clients.CC)); Free (Message.To (AWA.Mail.Clients.BCC)); end Finalize; procedure Initialize (Client : in out AWS_Mail_Manager'Class; Props : in Util.Properties.Manager'Class) is separate; -- ------------------------------ -- Create a SMTP based mail manager and configure it according to the properties. -- ------------------------------ function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost"); Port : constant String := Props.Get (Name => "smtp.port", Default => "25"); Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1"); Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager; begin Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port); Result.Port := Positive'Value (Port); Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true"; Result.Self := Result; Initialize (Result.all, Props); return Result.all'Access; end Create_Manager; -- ------------------------------ -- Create a new mail message. -- ------------------------------ overriding function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message; begin Result.Manager := Manager.Self; return Result.all'Access; end Create_Message; end AWA.Mail.Clients.AWS_SMTP;
Fix to collect the TO, CC, BCC recipients in separate lists and send the e-mail accordingly
Fix to collect the TO, CC, BCC recipients in separate lists and send the e-mail accordingly
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
89362fe01601837e1da47d589f1b175a37ffb548
awa/plugins/awa-questions/regtests/awa-questions-tests.adb
awa/plugins/awa-questions/regtests/awa-questions-tests.adb
----------------------------------------------------------------------- -- awa-questions-tests -- Unit tests for questions module -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with Servlet.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Questions.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Questions.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load (missing)", Test_Missing_Page'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save (answer)", Test_Answer_Question'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is function Get_Link (Title : in String) return String; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; function Get_Link (Title : in String) return String is Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title); end Get_Link; begin ASF.Tests.Do_Get (Request, Reply, "/questions/list.html", "question-list.html"); ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply, "Questions list page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/questions/tags/tag", "question-list-tagged.html"); ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply, "Questions tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/questions/view/" & Page, "question-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, Title, Reply, "Question page " & Page & " is invalid"); ASF.Tests.Assert_Matches (T, ".input type=.hidden. name=.question-id. " & "value=.[0-9]+. id=.question-id.../input", Reply, "Question page " & Page & " is invalid"); end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the question list contains the given question. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Id : in String; Title : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/list.html", "question-list-recent.html"); ASF.Tests.Assert_Contains (T, "Questions", Reply, "List of questions page is invalid"); ASF.Tests.Assert_Contains (T, "/questions/view/" & Id, Reply, "List of questions page does not reference the page"); ASF.Tests.Assert_Contains (T, Title, Reply, "List of questions page does not contain the question"); end Verify_List_Contains; -- ------------------------------ -- Test access to the question as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of question by simulating web requests. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is procedure Create_Question (Title : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; procedure Create_Question (Title : in String) is begin Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The question content." & ASCII.LF & "* Second item." & ASCII.LF); Request.Set_Parameter ("save", "1"); ASF.Tests.Do_Post (Request, Reply, "/questions/ask.html", "questions-ask.html"); T.Question_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/questions/view/"); Util.Tests.Assert_Matches (T, "[0-9]+$", To_String (T.Question_Ident), "Invalid redirect after question creation"); -- Remove the 'question' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("question"); end Create_Question; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Create_Question ("Question 1 page title1"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 1 page title1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 1 page title1"); Create_Question ("Question 2 page title2"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 2 page title2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 2 page title2"); Create_Question ("Question 3 page title3"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 3 page title3"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 3 page title3"); end Test_Create_Question; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/view.html?id=12345678", "question-page-missing.html"); ASF.Tests.Assert_Matches (T, "<title>Question not found</title>", Reply, "Question page title '12345678' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, "question.*removed", Reply, "Question page content '12345678' is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; -- ------------------------------ -- Test answer of question by simulating web requests. -- ------------------------------ procedure Test_Answer_Question (T : in out Test) is procedure Create_Answer (Content : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; procedure Create_Answer (Content : in String) is begin Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("question-id", To_String (T.Question_Ident)); Request.Set_Parameter ("answer-id", ""); Request.Set_Parameter ("text", Content); Request.Set_Parameter ("save", "1"); ASF.Tests.Do_Post (Request, Reply, "/questions/forms/answer-form.html", "questions-answer.html"); ASF.Tests.Assert_Contains (T, "/questions/view/" & To_String (T.Question_Ident), Reply, "Answer response is invalid"); -- Remove the 'question' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("answer"); end Create_Answer; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Create_Answer ("Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); Create_Answer ("Answer content 2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2"); Create_Answer ("Answer content 3"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 3"); end Test_Answer_Question; end AWA.Questions.Tests;
----------------------------------------------------------------------- -- awa-questions-tests -- Unit tests for questions module -- 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 ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Questions.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Questions.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load (missing)", Test_Missing_Page'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save (answer)", Test_Answer_Question'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/list.html", "question-list.html"); ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply, "Questions list page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/questions/tags/tag", "question-list-tagged.html"); ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply, "Questions tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/questions/view/" & Page, "question-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, Title, Reply, "Question page " & Page & " is invalid"); ASF.Tests.Assert_Matches (T, ".input type=.hidden. name=.question-id. " & "value=.[0-9]+. id=.question-id.../input", Reply, "Question page " & Page & " is invalid"); end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the question list contains the given question. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Id : in String; Title : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/list.html", "question-list-recent.html"); ASF.Tests.Assert_Contains (T, "Questions", Reply, "List of questions page is invalid"); ASF.Tests.Assert_Contains (T, "/questions/view/" & Id, Reply, "List of questions page does not reference the page"); ASF.Tests.Assert_Contains (T, Title, Reply, "List of questions page does not contain the question"); end Verify_List_Contains; -- ------------------------------ -- Test access to the question as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of question by simulating web requests. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is procedure Create_Question (Title : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; procedure Create_Question (Title : in String) is begin Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The question content." & ASCII.LF & "* Second item." & ASCII.LF); Request.Set_Parameter ("save", "1"); ASF.Tests.Do_Post (Request, Reply, "/questions/ask.html", "questions-ask.html"); T.Question_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/questions/view/"); Util.Tests.Assert_Matches (T, "[0-9]+$", To_String (T.Question_Ident), "Invalid redirect after question creation"); -- Remove the 'question' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("question"); end Create_Question; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Create_Question ("Question 1 page title1"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 1 page title1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 1 page title1"); Create_Question ("Question 2 page title2"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 2 page title2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 2 page title2"); Create_Question ("Question 3 page title3"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 3 page title3"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 3 page title3"); end Test_Create_Question; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/view.html?id=12345678", "question-page-missing.html"); ASF.Tests.Assert_Matches (T, "<title>Question not found</title>", Reply, "Question page title '12345678' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, "question.*removed", Reply, "Question page content '12345678' is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; -- ------------------------------ -- Test answer of question by simulating web requests. -- ------------------------------ procedure Test_Answer_Question (T : in out Test) is procedure Create_Answer (Content : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; procedure Create_Answer (Content : in String) is begin Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("question-id", To_String (T.Question_Ident)); Request.Set_Parameter ("answer-id", ""); Request.Set_Parameter ("text", Content); Request.Set_Parameter ("save", "1"); ASF.Tests.Do_Post (Request, Reply, "/questions/forms/answer-form.html", "questions-answer.html"); ASF.Tests.Assert_Contains (T, "/questions/view/" & To_String (T.Question_Ident), Reply, "Answer response is invalid"); -- Remove the 'question' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("answer"); end Create_Answer; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Create_Answer ("Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); Create_Answer ("Answer content 2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2"); Create_Answer ("Answer content 3"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 3"); end Test_Answer_Question; end AWA.Questions.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
47d995cfaceb81d9fa7f7d99b36e9d6a9a09bf6d
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- -- -- @include "security-contexts.ads" -- @include "security-controllers.ads" package Security is end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- -- -- @include security-contexts.ads -- @include security-controllers.ads package Security is end Security;
Fix documentation links
Fix documentation links
Ada
apache-2.0
Letractively/ada-security
b0492c71b2284963e32382177748aee08e3269d1
matp/src/events/mat-events-targets.ads
matp/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Finalization; with Util.Concurrent.Counters; with MAT.Events.Tools; package MAT.Events.Targets is type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. -- Update the event instance to allocate the event Id. procedure Insert (Target : in out Target_Events; Event : in out Target_Event_Type); -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Target : in out Target_Events; Id : in Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in Event_Id_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out MAT.Events.Tools.Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Target_Event_Type; -- Get the first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Target_Event_Type; Last : out Target_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Target_Event_Type)); -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event_Type)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Target_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Id : in Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in Event_Id_Type); -- Add the event in the list of events. -- Update the event instance to allocate the event Id. procedure Insert (Event : in out Target_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out MAT.Events.Tools.Target_Event_Vector); -- Get the first and last event that have been received. procedure Get_Limits (First : out Target_Event_Type; Last : out Target_Event_Type); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Target_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Target_Event_Type)); -- Clear the events. procedure Clear; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is new Ada.Finalization.Limited_Controlled with record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; -- Release the storage allocated for the events. overriding procedure Finalize (Target : in out Target_Events); end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Finalization; with Util.Concurrent.Counters; with MAT.Frames.Targets; with MAT.Events.Tools; package MAT.Events.Targets is type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. -- Update the event instance to allocate the event Id. procedure Insert (Target : in out Target_Events; Event : in out Target_Event_Type); -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Target : in out Target_Events; Id : in Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in Event_Id_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out MAT.Events.Tools.Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Target_Event_Type; -- Get the first and last event that have been received. procedure Get_Limits (Target : in out Target_Events; First : out Target_Event_Type; Last : out Target_Event_Type); -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Target_Event_Type)); -- Iterate over the events starting from first first event up to the last event collected. -- Execute the <tt>Process</tt> procedure with each event instance. procedure Iterate (Target : in out Target_Events; Process : access procedure (Event : in Target_Event_Type)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Target_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Id : in Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in Event_Id_Type); -- Add the event in the list of events. -- Update the event instance to allocate the event Id. procedure Insert (Event : in out Target_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out MAT.Events.Tools.Target_Event_Vector); -- Get the first and last event that have been received. procedure Get_Limits (First : out Target_Event_Type; Last : out Target_Event_Type); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Target_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Target_Event_Type)); -- Clear the events. procedure Clear; private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is new Ada.Finalization.Limited_Controlled with record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; -- Release the storage allocated for the events. overriding procedure Finalize (Target : in out Target_Events); end MAT.Events.Targets;
Fix compilation warning with GNAT 2018
Fix compilation warning with GNAT 2018
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6f0af6e548dcbe6bca30323ba13861dfd581fb66
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- 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) is Pos, Pos2, Slash_Pos, Next : Natural; Is_Hidden : Boolean; begin Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then Controller.Log_URI := To_Unbounded_String (URI (URI'First .. Pos)); while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); Append (Controller.Log_URI, URI (Pos + 1 .. Pos2)); Is_Hidden := URI (Pos + 1 .. Pos2 - 1) = "password"; if Is_Hidden then Append (Controller.Log_URI, "XXXXXXX"); end if; if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); if not Is_Hidden then Append (Controller.Log_URI, URI (Pos2 + 1 .. Next - 1)); end if; Append (Controller.Log_URI, "&"); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); if not Is_Hidden then Append (Controller.Log_URI, URI (Pos2 + 1 .. URI'Last)); end if; Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Append (Controller.Log_URI, URI (Pos + 1 .. URI'Last)); Pos := URI'Last; end if; end loop; else Controller.Log_URI := Controller.URI; end if; Log.Info ("Set connection URI: {0}", Controller.Log_URI); end Set_Connection; -- ------------------------------ -- 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) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Controller : in out Configuration; Database : in String) is begin Controller.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Get the database driver name. -- ------------------------------ function Get_Driver (Controller : in Configuration) return String is begin if Controller.Driver /= null then return Get_Driver_Name (Controller.Driver.all); else return ""; end if; end Get_Driver; -- ------------------------------ -- Get the database driver index. -- ------------------------------ function Get_Driver (Controller : in Configuration) return Driver_Index is begin if Controller.Driver /= null then return Controller.Driver.Index; else return Driver_Index'First; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.Log_URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); if Result.Is_Null then Log.Error ("Driver {0} failed to create connection {0}", Config.Driver.Name.all, To_String (Config.Log_URI)); raise Connection_Error with "Data source is not initialized: driver error"; end if; Log.Info ("Created connection to '{0}' -> {1}", Config.Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.Log_URI); raise; end Create_Connection; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database_Connection'Class (Database).Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- 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) is Pos, Pos2, Slash_Pos, Next : Natural; Is_Hidden : Boolean; begin Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then Controller.Log_URI := To_Unbounded_String (URI (URI'First .. Pos)); while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); Append (Controller.Log_URI, URI (Pos + 1 .. Pos2)); Is_Hidden := URI (Pos + 1 .. Pos2 - 1) = "password"; if Is_Hidden then Append (Controller.Log_URI, "XXXXXXX"); end if; if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); if not Is_Hidden then Append (Controller.Log_URI, URI (Pos2 + 1 .. Next - 1)); end if; Append (Controller.Log_URI, "&"); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); if not Is_Hidden then Append (Controller.Log_URI, URI (Pos2 + 1 .. URI'Last)); end if; Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Append (Controller.Log_URI, URI (Pos + 1 .. URI'Last)); Pos := URI'Last; end if; end loop; else Controller.Log_URI := Controller.URI; end if; Log.Info ("Set connection URI: {0}", Controller.Log_URI); end Set_Connection; -- ------------------------------ -- 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) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Controller : in out Configuration; Database : in String) is begin Controller.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Get the database driver name. -- ------------------------------ function Get_Driver (Controller : in Configuration) return String is begin if Controller.Driver /= null then return Get_Driver_Name (Controller.Driver.all); else return ""; end if; end Get_Driver; -- ------------------------------ -- Get the database driver index. -- ------------------------------ function Get_Driver (Controller : in Configuration) return Driver_Index is begin if Controller.Driver /= null then return Controller.Driver.Index; else return Driver_Index'First; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.Log_URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); if Result.Is_Null then Log.Error ("Driver {0} failed to create connection {0}", Config.Driver.Name.all, To_String (Config.Log_URI)); raise Connection_Error with "Data source is not initialized: driver error"; end if; Log.Info ("Created connection to '{0}' -> {1}", Config.Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.Log_URI); raise; end Create_Connection; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database_Connection'Class (Database).Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Fix style compilation warning
Fix style compilation warning
Ada
apache-2.0
stcarrez/ada-ado
e840784f517ce7ba3c14622cbe642db36bbc0da5
src/wiki-streams-html.ads
src/wiki-streams-html.ads
----------------------------------------------------------------------- -- wiki-streams-html -- Wiki HTML output stream -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Strings; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- -- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to -- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser -- repeatedly while scanning the Wiki content. package Wiki.Streams.Html is use Ada.Strings.Wide_Wide_Unbounded; type Html_Output_Stream_Type is limited interface and Output_Stream; type Html_Output_Stream_Access is access all Html_Output_Stream_Type'Class; -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Wide_Element (Writer : in out Html_Output_Stream_Type; Name : in String; Content : in Wiki.Strings.WString) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream_Type; Name : in String; Content : in Wide_Wide_String) is abstract; -- Start an XML element with the given name. procedure Start_Element (Writer : in out Html_Output_Stream_Type; Name : in String) is abstract; -- Closes an XML element of the given name. procedure End_Element (Writer : in out Html_Output_Stream_Type; Name : in String) is abstract; -- Write a text escaping any character as necessary. procedure Write_Wide_Text (Writer : in out Html_Output_Stream_Type; Content : in Wiki.Strings.WString) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Writer : in out Html_Output_Stream_Type'Class; Name : in String; Content : in String); end Wiki.Streams.Html;
----------------------------------------------------------------------- -- wiki-streams-html -- Wiki HTML output stream -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Strings; -- == Writer interfaces == -- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write -- their outputs. -- -- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to -- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser -- repeatedly while scanning the Wiki content. package Wiki.Streams.Html is use Ada.Strings.Wide_Wide_Unbounded; type Html_Output_Stream is limited interface and Output_Stream; type Html_Output_Stream_Access is access all Html_Output_Stream'Class; -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Wide_Element (Writer : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.WString) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream; Name : in String; Content : in Unbounded_Wide_Wide_String) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String) is abstract; -- Start an XML element with the given name. procedure Start_Element (Writer : in out Html_Output_Stream; Name : in String) is abstract; -- Closes an XML element of the given name. procedure End_Element (Writer : in out Html_Output_Stream; Name : in String) is abstract; -- Write a text escaping any character as necessary. procedure Write_Wide_Text (Writer : in out Html_Output_Stream; Content : in Wiki.Strings.WString) is abstract; -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Writer : in out Html_Output_Stream'Class; Name : in String; Content : in String); end Wiki.Streams.Html;
Use the Html_Output_Stream type for filter operations
Use the Html_Output_Stream type for filter operations
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f821f42ba626be911d4ac44272ee0eae786038ef
regtests/dlls/util-systems-dlls-tests.adb
regtests/dlls/util-systems-dlls-tests.adb
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; procedure Load_Library (T : in out Test; Lib : out Handle) is Lib1 : Handle; Lib2 : Handle; Lib3 : Handle; begin begin Lib1 := Util.Systems.DLLs.Load ("libcrypto.so"); T.Assert (Lib1 /= Null_Handle, "Load operation returned null"); Lib := Lib1; exception when Load_Error => Lib1 := Null_Handle; end; begin Lib2 := Util.Systems.DLLs.Load ("libcrypto.dylib"); T.Assert (Lib2 /= Null_Handle, "Load operation returned null"); Lib := Lib2; exception when Load_Error => Lib2 := Null_Handle; end; begin Lib3 := Util.Systems.DLLs.Load ("zlib1.dll"); T.Assert (Lib3 /= Null_Handle, "Load operation returned null"); Lib := Lib3; exception when Load_Error => Lib3 := Null_Handle; end; T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle, "At least on Load operation should have failedreturned null"); end Load_Library; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Load_Library (T, Lib); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address := System.Null_Address; begin Load_Library (T, Lib); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; -- We must have found one of the two symbols T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- Copyright (C) 2013, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Systems.DLLs.Tests is use Util.Tests; use type System.Address; procedure Load_Library (T : in out Test; Lib : out Handle); package Caller is new Util.Test_Caller (Test, "Systems.Dlls"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Util.Systems.Dlls.Get_Symbol", Test_Get_Symbol'Access); end Add_Tests; procedure Load_Library (T : in out Test; Lib : out Handle) is Lib1 : Handle; Lib2 : Handle; Lib3 : Handle; Lib4 : Handle; begin begin Lib1 := Util.Systems.DLLs.Load ("libcrypto.so"); T.Assert (Lib1 /= Null_Handle, "Load operation returned null"); Lib := Lib1; exception when Load_Error => Lib1 := Null_Handle; end; begin Lib2 := Util.Systems.DLLs.Load ("libcrypto.dylib"); T.Assert (Lib2 /= Null_Handle, "Load operation returned null"); Lib := Lib2; exception when Load_Error => Lib2 := Null_Handle; end; begin Lib3 := Util.Systems.DLLs.Load ("zlib1.dll"); T.Assert (Lib3 /= Null_Handle, "Load operation returned null"); Lib := Lib3; exception when Load_Error => Lib3 := Null_Handle; end; begin Lib4 := Util.Systems.DLLs.Load ("libz.so"); T.Assert (Lib4 /= Null_Handle, "Load operation returned null"); Lib := Lib4; exception when Load_Error => Lib4 := Null_Handle; end; T.Assert (Lib1 /= Null_Handle or Lib2 /= Null_Handle or Lib3 /= Null_Handle or Lib4 /= Null_Handle, "At least on Load operation should have failedreturned null"); end Load_Library; -- ------------------------------ -- Test the loading a shared library. -- ------------------------------ procedure Test_Load (T : in out Test) is Lib : Handle; begin Load_Library (T, Lib); begin Lib := Util.Systems.DLLs.Load ("some-invalid-library"); T.Fail ("Load must raise an exception"); exception when Load_Error => null; end; end Test_Load; -- ------------------------------ -- Test getting a shared library symbol. -- ------------------------------ procedure Test_Get_Symbol (T : in out Test) is Lib : Handle; Sym : System.Address := System.Null_Address; begin Load_Library (T, Lib); T.Assert (Lib /= Null_Handle, "Load operation returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "EVP_sha1"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "compress"); T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); exception when Not_Found => null; end; -- We must have found one of the two symbols T.Assert (Sym /= System.Null_Address, "Get_Symbol returned null"); begin Sym := Util.Systems.DLLs.Get_Symbol (Lib, "some-invalid-symbol"); T.Fail ("The Get_Symbol operation must raise an exception"); exception when Not_Found => null; end; end Test_Get_Symbol; end Util.Systems.DLLs.Tests;
Fix #7: try loading the libz shared library if libcrypto failed
Fix #7: try loading the libz shared library if libcrypto failed
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ee4b0cd627fc7e852fcc69911b7dc82e6390cb44
src/asf-contexts-flash.adb
src/asf-contexts-flash.adb
----------------------------------------------------------------------- -- contexts-facelets-flash -- Flash context -- 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 ASF.Sessions; with ASF.Applications.Messages.Utils; package body ASF.Contexts.Flash is -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Flash : in out Flash_Context; Name : in String; Value : in Util.Beans.Objects.Object) is Instance : Flash_Bean_Access; begin Flash.Get_Execute_Flash (Instance); if Util.Beans.Objects.Is_Null (Value) then Instance.Attributes.Delete (Name); else Instance.Attributes.Include (Name, Value); end if; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Flash : in out Flash_Context; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object) is begin Flash.Set_Attribute (To_String (Name), Value); end Set_Attribute; -- ------------------------------ -- Get the attribute with the given name from the 'previous' flash context. -- ------------------------------ function Get_Attribute (Flash : in Flash_Context; Name : in String) return Util.Beans.Objects.Object is begin if Flash.Previous = null then return Util.Beans.Objects.Null_Object; else declare Pos : constant Util.Beans.Objects.Maps.Cursor := Flash.Previous.Attributes.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then return Util.Beans.Objects.Maps.Element (Pos); else return Util.Beans.Objects.Null_Object; end if; end; end if; end Get_Attribute; -- Keep in the flash context the request attribute identified by the name <b>Name</b>. procedure Keep (Flash : in out Flash_Context; Name : in String) is begin null; end Keep; -- Returns True if the <b>Redirect</b> property was set on the previous flash instance. function Is_Redirect (Flash : in Flash_Context) return Boolean is begin return False; end Is_Redirect; -- Set this property to True to indicate to the next request on this session will be -- a redirect. After this call, the next request will return the <b>Redirect</b> value -- when the <b>Is_Redirect</b> function will be called. procedure Set_Redirect (Flash : in out Flash_Context; Redirect : in Boolean) is begin null; end Set_Redirect; -- ------------------------------ -- Returns True if the faces messages that are queued in the faces context must be -- preserved so they are accessible through the flash instance at the next request. -- ------------------------------ function Is_Keep_Messages (Flash : in Flash_Context) return Boolean is begin return Flash.Keep_Messages; end Is_Keep_Messages; -- ------------------------------ -- Set the keep messages property which controlls whether the faces messages -- that are queued in the faces context must be preserved so they are accessible through -- the flash instance at the next request. -- ------------------------------ procedure Set_Keep_Messages (Flash : in out Flash_Context; Value : in Boolean) is begin Flash.Keep_Messages := Value; end Set_Keep_Messages; -- ------------------------------ -- Perform any specific action before processing the phase referenced by <b>Phase</b>. -- This operation is used to restore the flash context for a new request. -- ------------------------------ procedure Do_Pre_Phase_Actions (Flash : in out Flash_Context; Phase : in ASF.Events.Phases.Phase_Type; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Events.Phases.Phase_Type; use type Util.Beans.Basic.Readonly_Bean_Access; begin -- Restore the flash bean instance from the session if there is one. if Phase = ASF.Events.Phases.RESTORE_VIEW then declare S : constant ASF.Sessions.Session := Context.Get_Session; B : access Util.Beans.Basic.Readonly_Bean'Class; begin if S.Is_Valid then Flash.Object := S.Get_Attribute ("asf.flash.bean"); B := Util.Beans.Objects.To_Bean (Flash.Object); if B /= null and then B.all in Flash_Bean'Class then Flash.Previous := Flash_Bean'Class (B.all)'Unchecked_Access; Context.Add_Messages ("", Flash.Previous.Messages); end if; end if; end; end if; end Do_Pre_Phase_Actions; -- ------------------------------ -- Perform any specific action after processing the phase referenced by <b>Phase</b>. -- This operation is used to save the flash context -- ------------------------------ procedure Do_Post_Phase_Actions (Flash : in out Flash_Context; Phase : in ASF.Events.Phases.Phase_Type; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Events.Phases.Phase_Type; begin if (Phase = ASF.Events.Phases.INVOKE_APPLICATION or Phase = ASF.Events.Phases.RENDER_RESPONSE) and then not Flash.Last_Phase_Done then Flash.Do_Last_Phase_Actions (Context); end if; end Do_Post_Phase_Actions; -- ------------------------------ -- Perform the last actions that must be made to save the flash context in the session. -- ------------------------------ procedure Do_Last_Phase_Actions (Flash : in out Flash_Context; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is S : ASF.Sessions.Session := Context.Get_Session; begin -- If we have to keep the messages, save them in the flash bean context if there are any. if Flash.Keep_Messages then declare Messages : constant Applications.Messages.Vectors.Cursor := Context.Get_Messages (""); begin if ASF.Applications.Messages.Vectors.Has_Element (Messages) then if Flash.Next = null then Flash.Next := new Flash_Bean; end if; ASF.Applications.Messages.Utils.Copy (Flash.Next.Messages, Messages); end if; end; end if; if S.Is_Valid then S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.Null_Object); elsif Flash.Next /= null then S := Context.Get_Session (Create => True); end if; if Flash.Next /= null then S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.To_Object (Flash.Next.all'Access)); end if; Flash.Last_Phase_Done := True; end Do_Last_Phase_Actions; procedure Get_Active_Flash (Flash : in out Flash_Context; Result : out Flash_Bean_Access) is begin if Flash.Previous = null then null; end if; Result := Flash.Previous; end Get_Active_Flash; procedure Get_Execute_Flash (Flash : in out Flash_Context; Result : out Flash_Bean_Access) is begin if Flash.Next = null then Flash.Next := new Flash_Bean; end if; Result := Flash.Next; end Get_Execute_Flash; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Flash_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; end ASF.Contexts.Flash;
----------------------------------------------------------------------- -- contexts-facelets-flash -- Flash context -- 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 ASF.Sessions; with ASF.Applications.Messages.Utils; package body ASF.Contexts.Flash is -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Flash : in out Flash_Context; Name : in String; Value : in Util.Beans.Objects.Object) is Instance : Flash_Bean_Access; begin Flash.Get_Execute_Flash (Instance); if Util.Beans.Objects.Is_Null (Value) then Instance.Attributes.Delete (Name); else Instance.Attributes.Include (Name, Value); end if; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Flash : in out Flash_Context; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object) is begin Flash.Set_Attribute (To_String (Name), Value); end Set_Attribute; -- ------------------------------ -- Get the attribute with the given name from the 'previous' flash context. -- ------------------------------ function Get_Attribute (Flash : in Flash_Context; Name : in String) return Util.Beans.Objects.Object is begin if Flash.Previous = null then return Util.Beans.Objects.Null_Object; else declare Pos : constant Util.Beans.Objects.Maps.Cursor := Flash.Previous.Attributes.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then return Util.Beans.Objects.Maps.Element (Pos); else return Util.Beans.Objects.Null_Object; end if; end; end if; end Get_Attribute; -- Keep in the flash context the request attribute identified by the name <b>Name</b>. procedure Keep (Flash : in out Flash_Context; Name : in String) is begin null; end Keep; -- ------------------------------ -- Returns True if the <b>Redirect</b> property was set on the previous flash instance. -- ------------------------------ function Is_Redirect (Flash : in Flash_Context) return Boolean is begin return Flash.Previous /= null and then Flash.Previous.Redirect; end Is_Redirect; -- Set this property to True to indicate to the next request on this session will be -- a redirect. After this call, the next request will return the <b>Redirect</b> value -- when the <b>Is_Redirect</b> function will be called. procedure Set_Redirect (Flash : in out Flash_Context; Redirect : in Boolean) is begin null; end Set_Redirect; -- ------------------------------ -- Returns True if the faces messages that are queued in the faces context must be -- preserved so they are accessible through the flash instance at the next request. -- ------------------------------ function Is_Keep_Messages (Flash : in Flash_Context) return Boolean is begin return Flash.Keep_Messages; end Is_Keep_Messages; -- ------------------------------ -- Set the keep messages property which controlls whether the faces messages -- that are queued in the faces context must be preserved so they are accessible through -- the flash instance at the next request. -- ------------------------------ procedure Set_Keep_Messages (Flash : in out Flash_Context; Value : in Boolean) is begin Flash.Keep_Messages := Value; end Set_Keep_Messages; -- ------------------------------ -- Perform any specific action before processing the phase referenced by <b>Phase</b>. -- This operation is used to restore the flash context for a new request. -- ------------------------------ procedure Do_Pre_Phase_Actions (Flash : in out Flash_Context; Phase : in ASF.Events.Phases.Phase_Type; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Events.Phases.Phase_Type; use type Util.Beans.Basic.Readonly_Bean_Access; begin -- Restore the flash bean instance from the session if there is one. if Phase = ASF.Events.Phases.RESTORE_VIEW then declare S : constant ASF.Sessions.Session := Context.Get_Session; B : access Util.Beans.Basic.Readonly_Bean'Class; begin if S.Is_Valid then Flash.Object := S.Get_Attribute ("asf.flash.bean"); B := Util.Beans.Objects.To_Bean (Flash.Object); if B /= null and then B.all in Flash_Bean'Class then Flash.Previous := Flash_Bean'Class (B.all)'Unchecked_Access; Context.Add_Messages ("", Flash.Previous.Messages); end if; end if; end; end if; end Do_Pre_Phase_Actions; -- ------------------------------ -- Perform any specific action after processing the phase referenced by <b>Phase</b>. -- This operation is used to save the flash context -- ------------------------------ procedure Do_Post_Phase_Actions (Flash : in out Flash_Context; Phase : in ASF.Events.Phases.Phase_Type; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Events.Phases.Phase_Type; begin if (Phase = ASF.Events.Phases.INVOKE_APPLICATION or Phase = ASF.Events.Phases.RENDER_RESPONSE) and then not Flash.Last_Phase_Done then Flash.Do_Last_Phase_Actions (Context); end if; end Do_Post_Phase_Actions; -- ------------------------------ -- Perform the last actions that must be made to save the flash context in the session. -- ------------------------------ procedure Do_Last_Phase_Actions (Flash : in out Flash_Context; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is S : ASF.Sessions.Session := Context.Get_Session; begin -- If we have to keep the messages, save them in the flash bean context if there are any. if Flash.Keep_Messages then declare Messages : constant Applications.Messages.Vectors.Cursor := Context.Get_Messages (""); begin if ASF.Applications.Messages.Vectors.Has_Element (Messages) then if Flash.Next = null then Flash.Next := new Flash_Bean; end if; ASF.Applications.Messages.Utils.Copy (Flash.Next.Messages, Messages); end if; end; end if; if S.Is_Valid then S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.Null_Object); elsif Flash.Next /= null then S := Context.Get_Session (Create => True); end if; if Flash.Next /= null then S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.To_Object (Flash.Next.all'Access)); end if; Flash.Last_Phase_Done := True; end Do_Last_Phase_Actions; procedure Get_Active_Flash (Flash : in out Flash_Context; Result : out Flash_Bean_Access) is begin if Flash.Previous = null then null; end if; Result := Flash.Previous; end Get_Active_Flash; procedure Get_Execute_Flash (Flash : in out Flash_Context; Result : out Flash_Bean_Access) is begin if Flash.Next = null then Flash.Next := new Flash_Bean; end if; Result := Flash.Next; end Get_Execute_Flash; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Flash_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; end ASF.Contexts.Flash;
Implement the Is_Redirect function
Implement the Is_Redirect function
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
8658941a560c9e0e64a779263abdab423887e257
src/gen-model-mappings.adb
src/gen-model-mappings.adb
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- 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 Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); elsif Name = "isNullable" then return Util.Beans.Objects.To_Object (From.Nullable); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_ENTITY_TYPE => return "entity_type"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- 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 Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); elsif Name = "isNullable" then return Util.Beans.Objects.To_Object (From.Nullable); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_ENTITY_TYPE => return "entity_type"; when T_BLOB => return "blob"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
Update name for the T_BLOB type
Update name for the T_BLOB type
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
bc6d2ac57d521c71506670af2a633d1589db4a8a
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Link : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Open_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; Line_Count : Natural := 0; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Remove Open_Paragraph procedure
Remove Open_Paragraph procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
10508eda0f6ead4f645a89980170733899a6f59d
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
Update according to the UML model
Update according to the UML model
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
f398cb3dead052a19cc0ef0300d00a963758e6b3
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Permission_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- 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.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Permission_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
Set the application context first to make sure it is ready for other operations (the application context is setup by the AWA service filter in real life, but this is not available for unit tests)
Set the application context first to make sure it is ready for other operations (the application context is setup by the AWA service filter in real life, but this is not available for unit tests)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b810ea19b4d14b5e638f26fd042f809a17c32a91
src/util-streams-texts.adb
src/util-streams-texts.adb
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- 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 Interfaces; with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; subtype Offset is Ada.Streams.Stream_Element_Offset; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access) is begin Stream.Initialize (Output => To, Input => null, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Char : in Character) is Buf : constant Ada.Streams.Stream_Element_Array (1 .. 1) := (1 => Ada.Streams.Stream_Element (Character'Pos (Char))); begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Print_Stream; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; Buf : Ada.Streams.Stream_Element_Array (1 .. 4); begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Buf (1) := Ada.Streams.Stream_Element (Val); Stream.Write (Buf (1 .. 1)); elsif Val <= 16#07FF# then Buf (1) := Stream_Element (16#C0# or Shift_Right (Val, 6)); Buf (2) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 2)); elsif Val <= 16#0FFFF# then Buf (1) := Stream_Element (16#E0# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (3) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 3)); else Val := Val and 16#1FFFFF#; Buf (1) := Stream_Element (16#F0# or Shift_Right (Val, 18)); Val := Val and 16#3FFFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (3) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (4) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 4)); end if; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in String) is Buf : Ada.Streams.Stream_Element_Array (Offset (Item'First) .. Offset (Item'Last)); for Buf'Address use Item'Address; begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C))); end loop; end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Buffered_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access) is begin Stream.Initialize (Output => null, Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
----------------------------------------------------------------------- -- util-streams-texts -- Text stream utilities -- 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 Interfaces; with Ada.IO_Exceptions; package body Util.Streams.Texts is use Ada.Streams; subtype Offset is Ada.Streams.Stream_Element_Offset; procedure Initialize (Stream : in out Print_Stream; To : in Output_Stream_Access) is begin Stream.Initialize (Output => To, Size => 4096); end Initialize; -- ------------------------------ -- Write a raw character on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Char : in Character) is Buf : constant Ada.Streams.Stream_Element_Array (1 .. 1) := (1 => Ada.Streams.Stream_Element (Character'Pos (Char))); begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. -- ------------------------------ procedure Write_Wide (Stream : in out Print_Stream; Item : in Wide_Wide_Character) is use Interfaces; Val : Unsigned_32; Buf : Ada.Streams.Stream_Element_Array (1 .. 4); begin -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx Val := Wide_Wide_Character'Pos (Item); if Val <= 16#7f# then Buf (1) := Ada.Streams.Stream_Element (Val); Stream.Write (Buf (1 .. 1)); elsif Val <= 16#07FF# then Buf (1) := Stream_Element (16#C0# or Shift_Right (Val, 6)); Buf (2) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 2)); elsif Val <= 16#0FFFF# then Buf (1) := Stream_Element (16#E0# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (3) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 3)); else Val := Val and 16#1FFFFF#; Buf (1) := Stream_Element (16#F0# or Shift_Right (Val, 18)); Val := Val and 16#3FFFF#; Buf (2) := Stream_Element (16#80# or Shift_Right (Val, 12)); Val := Val and 16#0FFF#; Buf (3) := Stream_Element (16#80# or Shift_Right (Val, 6)); Buf (4) := Stream_Element (16#80# or (Val and 16#03F#)); Stream.Write (Buf (1 .. 4)); end if; end Write_Wide; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in String) is Buf : Ada.Streams.Stream_Element_Array (Offset (Item'First) .. Offset (Item'Last)); for Buf'Address use Item'Address; begin Stream.Write (Buf); end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String) is Count : constant Natural := Ada.Strings.Unbounded.Length (Item); begin if Count > 0 then for I in 1 .. Count loop Stream.Write (Char => Ada.Strings.Unbounded.Element (Item, I)); end loop; end if; end Write; -- ------------------------------ -- Write a raw string on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Count : constant Natural := Ada.Strings.Wide_Wide_Unbounded.Length (Item); C : Wide_Wide_Character; begin if Count > 0 then for I in 1 .. Count loop C := Ada.Strings.Wide_Wide_Unbounded.Element (Item, I); Stream.Write (Char => Character'Val (Wide_Wide_Character'Pos (C))); end loop; end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Integer) is S : constant String := Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write an integer on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Long_Long_Integer) is S : constant String := Long_Long_Integer'Image (Item); begin if Item > 0 then Stream.Write (S (S'First + 1 .. S'Last)); else Stream.Write (S); end if; end Write; -- ------------------------------ -- Write a date on the stream. -- ------------------------------ procedure Write (Stream : in out Print_Stream; Item : in Ada.Calendar.Time; Format : in GNAT.Calendar.Time_IO.Picture_String := GNAT.Calendar.Time_IO.ISO_Date) is begin Stream.Write (GNAT.Calendar.Time_IO.Image (Item, Format)); end Write; -- ------------------------------ -- Get the output stream content as a string. -- ------------------------------ function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String is Size : constant Natural := Stream.Get_Size; Buffer : constant Streams.Buffered.Buffer_Access := Stream.Get_Buffer; Result : String (1 .. Size); begin for I in Result'Range loop Result (I) := Character'Val (Buffer (Stream_Element_Offset (I))); end loop; return Result; end To_String; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Character) is begin Stream.Write (Item); end Write_Char; -- ------------------------------ -- Write a character on the stream. -- ------------------------------ procedure Write_Char (Stream : in out Print_Stream'Class; Item : in Wide_Wide_Character) is begin Stream.Write_Wide (Item); end Write_Char; -- ------------------------------ -- Initialize the reader to read the input from the input stream given in <b>From</b>. -- ------------------------------ procedure Initialize (Stream : in out Reader_Stream; From : in Input_Stream_Access) is begin Stream.Initialize (Input => From, Size => 4096); end Initialize; -- ------------------------------ -- Read an input line from the input stream. The line is terminated by ASCII.LF. -- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed. -- ------------------------------ procedure Read_Line (Stream : in out Reader_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String; Strip : in Boolean := False) is C : Character; begin while not Stream.Is_Eof loop Stream.Read (C); if C = ASCII.LF then if not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; return; elsif C /= ASCII.CR or not Strip then Ada.Strings.Unbounded.Append (Into, C); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Read_Line; end Util.Streams.Texts;
Use the Output_Buffer_Stream for To_String operation Update calls to Initialize to setup the Output_Buffer_Stream or Input_Buffer_Stream
Use the Output_Buffer_Stream for To_String operation Update calls to Initialize to setup the Output_Buffer_Stream or Input_Buffer_Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a17a9d8ef760348e24c180bf5b4c6c424b6f3e65
src/ado-queries-loaders.adb
src/ado-queries-loaders.adb
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- 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 Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Query_List : Query_Definition_Access := null; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Query.File := File; Query.Next := File.Queries; File.Queries := Query; if File.Next = null and then Query_Files /= File then File.Next := Query_Files; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant ADO.Drivers.Driver_Access := ADO.Drivers.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration (T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32 is begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (Query : in Query_Definition_Access) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if Query.File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (Query); begin if Query.File.Last_Modified = M then return False; end if; Query.File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Into : in Query_File_Access) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Access; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (Into.File.all, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := new Query_Info; Into.Query_Def.Query := Into.Query; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if Into.Query /= null and Into.Driver >= 0 then Set_Query_Pattern (Into.Query.Main_Query (ADO.Drivers.Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if Into.Query /= null and Into.Driver >= 0 then Set_Query_Pattern (Into.Query.Count_Query (ADO.Drivers.Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading XML query {0}", Into.Path.all); Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Reader, Loader'Access); -- Read the XML query file. Reader.Parse (Into.Path.all); Into.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Into.Path.all); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Into : in Query_Definition_Access) is begin if Into.Query = null or else Is_Modified (Into) then Read_Query (Into.File); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Paths : in String; Load : in Boolean) is File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Path.all, Paths => Paths); begin File.Path := new String '(Path); if Load then Read_Query (File); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body Query is begin Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- 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 Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Query_List : Query_Definition_Access := null; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Query.File := File; Query.Next := File.Queries; File.Queries := Query; if File.Next = null and then Query_Files /= File then File.Next := Query_Files; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant ADO.Drivers.Driver_Access := ADO.Drivers.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration (T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (Query : in Query_Definition_Access) return Unsigned_32 is begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Query.File.Path.all)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Query.File.Path.all); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (Query : in Query_Definition_Access) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if Query.File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). Query.File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (Query); begin if Query.File.Last_Modified = M then return False; end if; Query.File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Into : in Query_File_Access) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Access; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (Into.File.all, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; Into.Query := null; if Into.Query_Def /= null then Into.Query := new Query_Info; Into.Query_Def.Query := Into.Query; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if Into.Query /= null and Into.Driver >= 0 then Set_Query_Pattern (Into.Query.Main_Query (ADO.Drivers.Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if Into.Query /= null and Into.Driver >= 0 then Set_Query_Pattern (Into.Query.Count_Query (ADO.Drivers.Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading XML query {0}", Into.Path.all); Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Reader.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Reader, Loader'Access); -- Read the XML query file. Reader.Parse (Into.Path.all); Into.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Into.Path.all); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Into : in Query_Definition_Access) is begin if Into.Query = null or else Is_Modified (Into) then Read_Query (Into.File); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Paths : in String; Load : in Boolean) is File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Path.all, Paths => Paths); begin File.Path := new String '(Path); if Load then Read_Query (File); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body Query is begin Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
Clear the reference to the query info when a new query is found
Clear the reference to the query info when a new query is found
Ada
apache-2.0
stcarrez/ada-ado
881e63179947f9c7fc7ee3b0c96bc11363ded373
src/asf-rest-definition.ads
src/asf-rest-definition.ads
----------------------------------------------------------------------- -- asf-rest-definition -- REST API Definition -- 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. ----------------------------------------------------------------------- generic type Object_Type is limited private; URI : String; package ASF.Rest.Definition is type Descriptor is new ASF.Rest.Descriptor with record Handler : access procedure (Object : in out Object_Type; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); end record; overriding procedure Dispatch (Handler : in Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); Entries : ASF.Rest.Descriptor_Access; generic Handler : access procedure (Object : in out Object_Type; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); Method : Method_Type; Pattern : String; Permission : Security.Permissions.Permission_Index; package Definition is Instance : aliased Descriptor; end Definition; end ASF.Rest.Definition;
----------------------------------------------------------------------- -- asf-rest-definition -- REST API Definition -- 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. ----------------------------------------------------------------------- generic type Object_Type is limited private; URI : String; package ASF.Rest.Definition is type Descriptor is new ASF.Rest.Descriptor with record Handler : access procedure (Object : in out Object_Type; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); end record; overriding procedure Dispatch (Handler : in Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); -- Definition of an API operation mapped to a given URI pattern and associated with -- the operation handler. generic Handler : access procedure (Object : in out Object_Type; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out ASF.Rest.Output_Stream'Class); Method : Method_Type; Pattern : String; Permission : Security.Permissions.Permission_Index; package Definition is Instance : aliased Descriptor; end Definition; -- Register the list of APIs that have been created by instantiating the <tt>Definition</tt> -- package. The REST servlet identified by <tt>Name</tt> is searched in the servlet registry -- and used as the servlet for processing the API requests. procedure Register (Registry : in out ASF.Servlets.Servlet_Registry; Name : in String; ELContext : in EL.Contexts.ELContext'Class); private Entries : ASF.Rest.Descriptor_Access; end ASF.Rest.Definition;
Declare the Register procedure and make the Entries member a private member
Declare the Register procedure and make the Entries member a private member
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
fc72f3851ff3277c4b626a83f5f85b4c926e83fc
testcases/ds_fetch/ds_fetch.adb
testcases/ds_fetch/ds_fetch.adb
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with AdaBase.Results.Sets; procedure DS_Fetch is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; row : ARS.DataRow_Access; sql : constant String := "SELECT * FROM fruits WHERE color = 'orange'"; begin declare begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; CON.STMT := CON.DR.query (sql); TIO.Put_Line (" Query successful: " & CON.STMT.successful'Img); TIO.Put_Line (" Data Discarded: " & CON.STMT.data_discarded'Img); TIO.Put_Line ("Number of columns:" & CON.STMT.column_count'Img); TIO.Put_Line (" Number of rows:" & CON.STMT.rows_returned'Img); TIO.Put_Line (""); for c in Natural range 1 .. CON.STMT.column_count loop TIO.Put_Line ("Column" & c'Img & ":"); TIO.Put_Line (" TABLE: " & CON.STMT.column_table (c)); TIO.Put_Line (" NAME: " & CON.STMT.column_name (c)); TIO.Put_Line (" TYPE: " & CON.STMT.column_native_type (c)'Img); end loop; TIO.Put_Line (""); loop exit when not CON.STMT.fetch_next (row); TIO.Put (CT.zeropad (Natural (row.column (1).as_byte2), 2) & " "); declare fruit : String := row.column ("fruit").as_string; frlen : Natural := fruit'Length; rest : String (1 .. 12 - frlen) := (others => ' '); begin TIO.Put (rest & fruit); end; TIO.Put (" (" & row.column ("color").as_string & ") calories ="); TIO.Put_Line (row.column (4).as_byte2'Img); end loop; CON.DR.disconnect; end DS_Fetch;
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with AdaBase.Results.Sets; procedure DS_Fetch is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; begin begin CON.connect_database; exception when others => TIO.Put_Line ("database connect failed."); return; end; declare sql : constant String := "SELECT * FROM fruits WHERE color = 'orange'"; stmt : CON.Stmt_Type := CON.DR.query (sql); row : ARS.DataRow; begin TIO.Put_Line (" Query successful: " & stmt.successful'Img); TIO.Put_Line (" Data Discarded: " & stmt.data_discarded'Img); TIO.Put_Line ("Number of columns:" & stmt.column_count'Img); TIO.Put_Line (" Number of rows:" & stmt.rows_returned'Img); TIO.Put_Line (""); for c in Natural range 1 .. stmt.column_count loop TIO.Put_Line ("Column" & c'Img & ":"); TIO.Put_Line (" TABLE: " & stmt.column_table (c)); TIO.Put_Line (" NAME: " & stmt.column_name (c)); TIO.Put_Line (" TYPE: " & stmt.column_native_type (c)'Img); end loop; TIO.Put_Line (""); loop row := stmt.fetch_next; exit when row.data_exhausted; TIO.Put (CT.zeropad (Natural (row.column (1).as_byte2), 2) & " "); declare fruit : String := row.column ("fruit").as_string; frlen : Natural := fruit'Length; rest : String (1 .. 12 - frlen) := (others => ' '); begin TIO.Put (rest & fruit); end; TIO.Put (" (" & row.column ("color").as_string & ") calories ="); TIO.Put_Line (row.column (4).as_byte2'Img); end loop; end; CON.DR.disconnect; end DS_Fetch;
fix ds_fetch test case
fix ds_fetch test case
Ada
isc
jrmarino/AdaBase
42cb9479cd9c51fb0da44d2f47e4c10b290a010a
src/drivers/ado-drivers.ads
src/drivers/ado-drivers.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- == Database Drivers == -- Database drivers provide operations to access the database. These operations are -- specific to the database type and the `ADO.Drivers` package among others provide -- an abstraction that allows to make the different databases look like they have almost -- the same interface. -- -- A database driver exists for SQLite, MySQL and PostgreSQL. The driver -- is either statically linked to the application or it can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by `libada_ado_`. For example, for a `mysql` driver, the shared -- library name is `libada_ado_mysql.so`. -- -- | Driver name | Database | -- | ----------- | --------- | -- | mysql | MySQL, MariaDB | -- | sqlite | SQLite | -- | postgresql | PostgreSQL | -- -- The database drivers are initialized automatically but in some cases, you may want -- to control some database driver configuration parameter. In that case, -- the initialization must be done only once before creating a session -- factory and getting a database connection. The initialization can be made using -- a property file which contains the configuration for the database drivers and -- the database connection properties. For such initialization, you will have to -- call one of the `Initialize` operation from the `ADO.Drivers` package. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "sqlite:///mydatabase.db"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Drivers.Initialize (Config); -- -- Once initialized, a configuration property can be retrieved by using the `Get_Config` -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- -- Dynamic loading of database drivers is disabled by default for security reasons and -- it can be enabled by setting the following property in the configuration file: -- -- ado.drivers.load=true -- -- Dynamic loading is triggered when a database connection string refers to a database -- driver which is not known. -- -- @include ado-mysql.ads -- @include ado-sqlite.ads -- @include ado-postgresql.ads package ADO.Drivers is -- Raised for all errors reported by the database. Database_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; -- Returns true if the global configuration property is set to true/on. function Is_On (Name : in String) return Boolean; -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 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.Properties; -- == Database Drivers == -- Database drivers provide operations to access the database. These operations are -- specific to the database type and the `ADO.Drivers` package among others provide -- an abstraction that allows to make the different databases look like they have almost -- the same interface. -- -- A database driver exists for SQLite, MySQL and PostgreSQL. The driver -- is either statically linked to the application or it can be loaded dynamically if it was -- built as a shared library. For a dynamic load, the driver shared library name must be -- prefixed by `libada_ado_`. For example, for a `mysql` driver, the shared -- library name is `libada_ado_mysql.so`. -- -- | Driver name | Database | -- | ----------- | --------- | -- | mysql | MySQL, MariaDB | -- | sqlite | SQLite | -- | postgresql | PostgreSQL | -- -- The database drivers are initialized automatically but in some cases, you may want -- to control some database driver configuration parameter. In that case, -- the initialization must be done only once before creating a session -- factory and getting a database connection. The initialization can be made using -- a property file which contains the configuration for the database drivers and -- the database connection properties. For such initialization, you will have to -- call one of the `Initialize` operation from the `ADO.Drivers` package. -- -- ADO.Drivers.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "sqlite:///mydatabase.db"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Drivers.Initialize (Config); -- -- Once initialized, a configuration property can be retrieved by using the `Get_Config` -- operation. -- -- URI : constant String := ADO.Drivers.Get_Config ("ado.database"); -- -- Dynamic loading of database drivers is disabled by default for security reasons and -- it can be enabled by setting the following property in the configuration file: -- -- ado.drivers.load=true -- -- Dynamic loading is triggered when a database connection string refers to a database -- driver which is not known. -- -- @include ado-mysql.ads -- @include ado-sqlite.ads -- @include ado-postgresql.ads package ADO.Drivers is -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Initialize the drivers which are available. procedure Initialize; end ADO.Drivers;
Remove Database_Error, Driver_Index, Get_Config, Is_On to avoid confusion with operations in ADO.Configs package
Remove Database_Error, Driver_Index, Get_Config, Is_On to avoid confusion with operations in ADO.Configs package
Ada
apache-2.0
stcarrez/ada-ado
d1662667c85822486e1f3719853c25f799cf47ec
tools/smaz.adb
tools/smaz.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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Command Line Interface for primitives in Natools.Smaz.Tools. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Command_Line; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Text_IO.Text_Streams; with Natools.Getopt_Long; with Natools.S_Expressions.Parsers; with Natools.S_Expressions.Printers; with Natools.Smaz.Tools; with Natools.Smaz.Tools.GNAT; procedure Smaz is package Actions is type Enum is (Nothing, Encode); end Actions; package Options is type Id is (Output_Ada_Dictionary, Encode, Output_Hash, Help, Stat_Output, No_Stat_Output, Sx_Output, No_Sx_Output); end Options; package Getopt is new Natools.Getopt_Long (Options.Id); type Callback is new Getopt.Handlers.Callback with record Display_Help : Boolean := False; Need_Dictionary : Boolean := False; Stat_Output : Boolean := False; Sx_Output : Boolean := False; Action : Actions.Enum := Actions.Nothing; Ada_Dictionary : Ada.Strings.Unbounded.Unbounded_String; Hash_Package : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String); overriding procedure Argument (Handler : in out Callback; Argument : in String) is null; function Getopt_Config return Getopt.Configuration; -- Build the configuration object procedure Print_Dictionary (Filename : in String; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := ""); procedure Print_Dictionary (Output : in Ada.Text_IO.File_Type; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := ""); -- print the given dictionary in the given file procedure Print_Help (Opt : in Getopt.Configuration; Output : in Ada.Text_IO.File_Type); -- Print the help text to the given file overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String) is begin case Id is when Options.Help => Handler.Display_Help := True; when Options.Encode => Handler.Need_Dictionary := True; Handler.Action := Actions.Encode; when Options.No_Stat_Output => Handler.Stat_Output := False; when Options.No_Sx_Output => Handler.Sx_Output := False; when Options.Output_Ada_Dictionary => Handler.Need_Dictionary := True; if Argument'Length > 0 then Handler.Ada_Dictionary := Ada.Strings.Unbounded.To_Unbounded_String (Argument); else Handler.Ada_Dictionary := Ada.Strings.Unbounded.To_Unbounded_String ("-"); end if; when Options.Output_Hash => Handler.Need_Dictionary := True; Handler.Hash_Package := Ada.Strings.Unbounded.To_Unbounded_String (Argument); when Options.Stat_Output => Handler.Stat_Output := True; when Options.Sx_Output => Handler.Sx_Output := True; end case; end Option; function Getopt_Config return Getopt.Configuration is use Getopt; use Options; R : Getopt.Configuration; begin R.Add_Option ("ada-dict", 'A', Optional_Argument, Output_Ada_Dictionary); R.Add_Option ("encode", 'e', No_Argument, Encode); R.Add_Option ("help", 'h', No_Argument, Help); R.Add_Option ("hash-pkg", 'H', Required_Argument, Output_Hash); R.Add_Option ("stats", 's', No_Argument, Stat_Output); R.Add_Option ("no-stats", 'S', No_Argument, No_Stat_Output); R.Add_Option ("s-expr", 'x', No_Argument, Sx_Output); R.Add_Option ("no-s-expr", 'X', No_Argument, No_Sx_Output); return R; end Getopt_Config; procedure Print_Dictionary (Filename : in String; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := "") is begin if Filename = "-" then Print_Dictionary (Ada.Text_IO.Current_Output, Dictionary, Hash_Package_Name); elsif Filename'Length > 0 then declare File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File, Name => Filename); Print_Dictionary (File, Dictionary, Hash_Package_Name); Ada.Text_IO.Close (File); end; end if; end Print_Dictionary; procedure Print_Dictionary (Output : in Ada.Text_IO.File_Type; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := "") is procedure Put_Line (Line : in String); procedure Put_Line (Line : in String) is begin Ada.Text_IO.Put_Line (Output, Line); end Put_Line; procedure Print_Dictionary_In_Ada is new Natools.Smaz.Tools.Print_Dictionary_In_Ada (Put_Line); begin if Hash_Package_Name'Length > 0 then Print_Dictionary_In_Ada (Dictionary, Hash_Image => Hash_Package_Name & ".Hash'Access"); else Print_Dictionary_In_Ada (Dictionary); end if; end Print_Dictionary; procedure Print_Help (Opt : in Getopt.Configuration; Output : in Ada.Text_IO.File_Type) is use Ada.Text_IO; Indent : constant String := " "; begin Put_Line (Output, "Usage:"); for Id in Options.Id loop Put (Output, Indent & Opt.Format_Names (Id)); case Id is when Options.Help => New_Line (Output); Put_Line (Output, Indent & Indent & "Display this help text"); when Options.Encode => New_Line (Output); Put_Line (Output, Indent & Indent & "Read a list of strings and encode them"); when Options.No_Stat_Output => New_Line (Output); Put_Line (Output, Indent & Indent & "Do not output filter statistics"); when Options.No_Sx_Output => New_Line (Output); Put_Line (Output, Indent & Indent & "Do not output filtered results in a S-expression"); when Options.Output_Ada_Dictionary => Put_Line (Output, "=[filename]"); Put_Line (Output, Indent & Indent & "Output the current dictionary as Ada code in the given"); Put_Line (Output, Indent & Indent & "file, or standard output if filename is ""-"""); when Options.Output_Hash => Put_Line (Output, " <Hash Package Name>"); Put_Line (Output, Indent & Indent & "Build a package with a perfect hash function for the"); Put_Line (Output, Indent & Indent & "current dictionary."); when Options.Stat_Output => New_Line (Output); Put_Line (Output, Indent & Indent & "Output filter statistics"); when Options.Sx_Output => New_Line (Output); Put_Line (Output, Indent & Indent & "Output filtered results in a S-expression"); end case; end loop; end Print_Help; Opt_Config : constant Getopt.Configuration := Getopt_Config; Handler : Callback; Input_List, Input_Data : Natools.Smaz.Tools.String_Lists.List; begin Process_Command_Line : begin Opt_Config.Process (Handler); exception when Getopt.Option_Error => Print_Help (Opt_Config, Ada.Text_IO.Current_Error); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end Process_Command_Line; if Handler.Display_Help then Print_Help (Opt_Config, Ada.Text_IO.Current_Output); end if; if not Handler.Need_Dictionary then return; end if; if not (Handler.Stat_Output or Handler.Sx_Output) then Handler.Sx_Output := True; end if; Read_Input_List : declare use type Actions.Enum; Input : constant access Ada.Streams.Root_Stream_Type'Class := Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input); Parser : Natools.S_Expressions.Parsers.Stream_Parser (Input); begin Parser.Next; Natools.Smaz.Tools.Read_List (Input_List, Parser); if Handler.Action /= Actions.Nothing then Parser.Next; Natools.Smaz.Tools.Read_List (Input_Data, Parser); end if; end Read_Input_List; Build_Dictionary : declare Dictionary : Natools.Smaz.Dictionary := Natools.Smaz.Tools.To_Dictionary (Input_List, True); Sx_Output : Natools.S_Expressions.Printers.Canonical (Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Output)); Ada_Dictionary : constant String := Ada.Strings.Unbounded.To_String (Handler.Ada_Dictionary); Hash_Package : constant String := Ada.Strings.Unbounded.To_String (Handler.Hash_Package); begin Dictionary.Hash := Natools.Smaz.Tools.Linear_Search'Access; Natools.Smaz.Tools.List_For_Linear_Search := Input_List; if Ada_Dictionary'Length > 0 then Print_Dictionary (Ada_Dictionary, Dictionary, Hash_Package); end if; if Hash_Package'Length > 0 then Natools.Smaz.Tools.GNAT.Build_Perfect_Hash (Input_List, Hash_Package); end if; case Handler.Action is when Actions.Nothing => null; when Actions.Encode => if Handler.Sx_Output then Sx_Output.Open_List; for S of Input_Data loop Sx_Output.Append_Atom (Natools.Smaz.Compress (Dictionary, S)); end loop; Sx_Output.Close_List; end if; if Handler.Stat_Output then declare procedure Print_Line (Original, Output, Base64 : Natural); procedure Print_Line (Original, Output, Base64 : Natural) is begin Ada.Text_IO.Put_Line (Natural'Image (Original) & Ada.Characters.Latin_1.HT & Natural'Image (Output) & Ada.Characters.Latin_1.HT & Natural'Image (Base64) & Ada.Characters.Latin_1.HT & Float'Image (Float (Output) / Float (Original)) & Ada.Characters.Latin_1.HT & Float'Image (Float (Base64) / Float (Original))); end Print_Line; Original_Total : Natural := 0; Output_Total : Natural := 0; Base64_Total : Natural := 0; begin for S of Input_Data loop declare Original_Size : constant Natural := S'Length; Output_Size : constant Natural := Natools.Smaz.Compress (Dictionary, S)'Length; Base64_Size : constant Natural := ((Output_Size + 2) / 3) * 4; begin Print_Line (Original_Size, Output_Size, Base64_Size); Original_Total := Original_Total + Original_Size; Output_Total := Output_Total + Output_Size; Base64_Total := Base64_Total + Base64_Size; end; end loop; Print_Line (Original_Total, Output_Total, Base64_Total); end; end if; end case; end Build_Dictionary; end Smaz;
------------------------------------------------------------------------------ -- 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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Command Line Interface for primitives in Natools.Smaz.Tools. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Command_Line; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Text_IO.Text_Streams; with Natools.Getopt_Long; with Natools.S_Expressions.Parsers; with Natools.S_Expressions.Printers; with Natools.Smaz.Tools; with Natools.Smaz.Tools.GNAT; procedure Smaz is function To_SEA (S : String) return Ada.Streams.Stream_Element_Array renames Natools.S_Expressions.To_Atom; package Actions is type Enum is (Nothing, Decode, Encode); end Actions; package Options is type Id is (Output_Ada_Dictionary, Decode, Encode, Output_Hash, Help, Stat_Output, No_Stat_Output, Sx_Output, No_Sx_Output); end Options; package Getopt is new Natools.Getopt_Long (Options.Id); type Callback is new Getopt.Handlers.Callback with record Display_Help : Boolean := False; Need_Dictionary : Boolean := False; Stat_Output : Boolean := False; Sx_Output : Boolean := False; Action : Actions.Enum := Actions.Nothing; Ada_Dictionary : Ada.Strings.Unbounded.Unbounded_String; Hash_Package : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String); overriding procedure Argument (Handler : in out Callback; Argument : in String) is null; function Getopt_Config return Getopt.Configuration; -- Build the configuration object procedure Print_Dictionary (Filename : in String; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := ""); procedure Print_Dictionary (Output : in Ada.Text_IO.File_Type; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := ""); -- print the given dictionary in the given file procedure Print_Help (Opt : in Getopt.Configuration; Output : in Ada.Text_IO.File_Type); -- Print the help text to the given file overriding procedure Option (Handler : in out Callback; Id : in Options.Id; Argument : in String) is begin case Id is when Options.Help => Handler.Display_Help := True; when Options.Decode => Handler.Need_Dictionary := True; Handler.Action := Actions.Decode; when Options.Encode => Handler.Need_Dictionary := True; Handler.Action := Actions.Encode; when Options.No_Stat_Output => Handler.Stat_Output := False; when Options.No_Sx_Output => Handler.Sx_Output := False; when Options.Output_Ada_Dictionary => Handler.Need_Dictionary := True; if Argument'Length > 0 then Handler.Ada_Dictionary := Ada.Strings.Unbounded.To_Unbounded_String (Argument); else Handler.Ada_Dictionary := Ada.Strings.Unbounded.To_Unbounded_String ("-"); end if; when Options.Output_Hash => Handler.Need_Dictionary := True; Handler.Hash_Package := Ada.Strings.Unbounded.To_Unbounded_String (Argument); when Options.Stat_Output => Handler.Stat_Output := True; when Options.Sx_Output => Handler.Sx_Output := True; end case; end Option; function Getopt_Config return Getopt.Configuration is use Getopt; use Options; R : Getopt.Configuration; begin R.Add_Option ("ada-dict", 'A', Optional_Argument, Output_Ada_Dictionary); R.Add_Option ("decode", 'd', No_Argument, Decode); R.Add_Option ("encode", 'e', No_Argument, Encode); R.Add_Option ("help", 'h', No_Argument, Help); R.Add_Option ("hash-pkg", 'H', Required_Argument, Output_Hash); R.Add_Option ("stats", 's', No_Argument, Stat_Output); R.Add_Option ("no-stats", 'S', No_Argument, No_Stat_Output); R.Add_Option ("s-expr", 'x', No_Argument, Sx_Output); R.Add_Option ("no-s-expr", 'X', No_Argument, No_Sx_Output); return R; end Getopt_Config; procedure Print_Dictionary (Filename : in String; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := "") is begin if Filename = "-" then Print_Dictionary (Ada.Text_IO.Current_Output, Dictionary, Hash_Package_Name); elsif Filename'Length > 0 then declare File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File, Name => Filename); Print_Dictionary (File, Dictionary, Hash_Package_Name); Ada.Text_IO.Close (File); end; end if; end Print_Dictionary; procedure Print_Dictionary (Output : in Ada.Text_IO.File_Type; Dictionary : in Natools.Smaz.Dictionary; Hash_Package_Name : in String := "") is procedure Put_Line (Line : in String); procedure Put_Line (Line : in String) is begin Ada.Text_IO.Put_Line (Output, Line); end Put_Line; procedure Print_Dictionary_In_Ada is new Natools.Smaz.Tools.Print_Dictionary_In_Ada (Put_Line); begin if Hash_Package_Name'Length > 0 then Print_Dictionary_In_Ada (Dictionary, Hash_Image => Hash_Package_Name & ".Hash'Access"); else Print_Dictionary_In_Ada (Dictionary); end if; end Print_Dictionary; procedure Print_Help (Opt : in Getopt.Configuration; Output : in Ada.Text_IO.File_Type) is use Ada.Text_IO; Indent : constant String := " "; begin Put_Line (Output, "Usage:"); for Id in Options.Id loop Put (Output, Indent & Opt.Format_Names (Id)); case Id is when Options.Help => New_Line (Output); Put_Line (Output, Indent & Indent & "Display this help text"); when Options.Decode => New_Line (Output); Put_Line (Output, Indent & Indent & "Read a list of strings and decode them"); when Options.Encode => New_Line (Output); Put_Line (Output, Indent & Indent & "Read a list of strings and encode them"); when Options.No_Stat_Output => New_Line (Output); Put_Line (Output, Indent & Indent & "Do not output filter statistics"); when Options.No_Sx_Output => New_Line (Output); Put_Line (Output, Indent & Indent & "Do not output filtered results in a S-expression"); when Options.Output_Ada_Dictionary => Put_Line (Output, "=[filename]"); Put_Line (Output, Indent & Indent & "Output the current dictionary as Ada code in the given"); Put_Line (Output, Indent & Indent & "file, or standard output if filename is ""-"""); when Options.Output_Hash => Put_Line (Output, " <Hash Package Name>"); Put_Line (Output, Indent & Indent & "Build a package with a perfect hash function for the"); Put_Line (Output, Indent & Indent & "current dictionary."); when Options.Stat_Output => New_Line (Output); Put_Line (Output, Indent & Indent & "Output filter statistics"); when Options.Sx_Output => New_Line (Output); Put_Line (Output, Indent & Indent & "Output filtered results in a S-expression"); end case; end loop; end Print_Help; Opt_Config : constant Getopt.Configuration := Getopt_Config; Handler : Callback; Input_List, Input_Data : Natools.Smaz.Tools.String_Lists.List; begin Process_Command_Line : begin Opt_Config.Process (Handler); exception when Getopt.Option_Error => Print_Help (Opt_Config, Ada.Text_IO.Current_Error); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end Process_Command_Line; if Handler.Display_Help then Print_Help (Opt_Config, Ada.Text_IO.Current_Output); end if; if not Handler.Need_Dictionary then return; end if; if not (Handler.Stat_Output or Handler.Sx_Output) then Handler.Sx_Output := True; end if; Read_Input_List : declare use type Actions.Enum; Input : constant access Ada.Streams.Root_Stream_Type'Class := Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input); Parser : Natools.S_Expressions.Parsers.Stream_Parser (Input); begin Parser.Next; Natools.Smaz.Tools.Read_List (Input_List, Parser); if Handler.Action /= Actions.Nothing then Parser.Next; Natools.Smaz.Tools.Read_List (Input_Data, Parser); end if; end Read_Input_List; Build_Dictionary : declare Dictionary : Natools.Smaz.Dictionary := Natools.Smaz.Tools.To_Dictionary (Input_List, True); Sx_Output : Natools.S_Expressions.Printers.Canonical (Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Output)); Ada_Dictionary : constant String := Ada.Strings.Unbounded.To_String (Handler.Ada_Dictionary); Hash_Package : constant String := Ada.Strings.Unbounded.To_String (Handler.Hash_Package); begin Dictionary.Hash := Natools.Smaz.Tools.Linear_Search'Access; Natools.Smaz.Tools.List_For_Linear_Search := Input_List; if Ada_Dictionary'Length > 0 then Print_Dictionary (Ada_Dictionary, Dictionary, Hash_Package); end if; if Hash_Package'Length > 0 then Natools.Smaz.Tools.GNAT.Build_Perfect_Hash (Input_List, Hash_Package); end if; case Handler.Action is when Actions.Nothing => null; when Actions.Decode => if Handler.Sx_Output then Sx_Output.Open_List; for S of Input_Data loop Sx_Output.Append_String (Natools.Smaz.Decompress (Dictionary, To_SEA (S))); end loop; Sx_Output.Close_List; end if; if Handler.Stat_Output then declare procedure Print_Line (Original, Output : Natural); procedure Print_Line (Original, Output : Natural) is begin Ada.Text_IO.Put_Line (Natural'Image (Original) & Ada.Characters.Latin_1.HT & Natural'Image (Output) & Ada.Characters.Latin_1.HT & Float'Image (Float (Original) / Float (Output))); end Print_Line; Original_Total : Natural := 0; Output_Total : Natural := 0; begin for S of Input_Data loop declare Original_Size : constant Natural := S'Length; Output_Size : constant Natural := Natools.Smaz.Decompress (Dictionary, To_SEA (S))'Length; begin Print_Line (Original_Size, Output_Size); Original_Total := Original_Total + Original_Size; Output_Total := Output_Total + Output_Size; end; end loop; Print_Line (Original_Total, Output_Total); end; end if; when Actions.Encode => if Handler.Sx_Output then Sx_Output.Open_List; for S of Input_Data loop Sx_Output.Append_Atom (Natools.Smaz.Compress (Dictionary, S)); end loop; Sx_Output.Close_List; end if; if Handler.Stat_Output then declare procedure Print_Line (Original, Output, Base64 : Natural); procedure Print_Line (Original, Output, Base64 : Natural) is begin Ada.Text_IO.Put_Line (Natural'Image (Original) & Ada.Characters.Latin_1.HT & Natural'Image (Output) & Ada.Characters.Latin_1.HT & Natural'Image (Base64) & Ada.Characters.Latin_1.HT & Float'Image (Float (Output) / Float (Original)) & Ada.Characters.Latin_1.HT & Float'Image (Float (Base64) / Float (Original))); end Print_Line; Original_Total : Natural := 0; Output_Total : Natural := 0; Base64_Total : Natural := 0; begin for S of Input_Data loop declare Original_Size : constant Natural := S'Length; Output_Size : constant Natural := Natools.Smaz.Compress (Dictionary, S)'Length; Base64_Size : constant Natural := ((Output_Size + 2) / 3) * 4; begin Print_Line (Original_Size, Output_Size, Base64_Size); Original_Total := Original_Total + Original_Size; Output_Total := Output_Total + Output_Size; Base64_Total := Base64_Total + Base64_Size; end; end loop; Print_Line (Original_Total, Output_Total, Base64_Total); end; end if; end case; end Build_Dictionary; end Smaz;
add decompression of an input list of encoded strings
tools/smaz: add decompression of an input list of encoded strings
Ada
isc
faelys/natools
45b47bab4dc8b449ba8b16d8345d7925cf992e87
src/el-contexts-default.adb
src/el-contexts-default.adb
----------------------------------------------------------------------- -- EL.Contexts -- Default contexts for evaluating an expression -- 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.Unchecked_Deallocation; with EL.Variables.Default; package body EL.Contexts.Default is procedure Free is new Ada.Unchecked_Deallocation (Object => EL.Variables.Variable_Mapper'Class, Name => EL.Variables.Variable_Mapper_Access); -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : Default_Context) return ELResolver_Access is begin return Context.Resolver; end Get_Resolver; -- ------------------------------ -- Set the ELResolver associated with this ELcontext. -- ------------------------------ procedure Set_Resolver (Context : in out Default_Context; Resolver : in ELResolver_Access) is begin Context.Resolver := Resolver; end Set_Resolver; -- ------------------------------ -- Retrieves the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : Default_Context) return access EL.Variables.Variable_Mapper'Class is begin return Context.Var_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the Function_Mapper associated with this ELContext. -- The Function_Mapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : Default_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Default_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin if Mapper = null then Context.Function_Mapper := null; else Context.Function_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Function_Mapper; -- ------------------------------ -- Set the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Default_Context; Mapper : access EL.Variables.Variable_Mapper'Class) is use EL.Variables; begin if Context.Var_Mapper_Created then Free (Context.Var_Mapper); end if; if Mapper = null then Context.Var_Mapper := null; else Context.Var_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Variable_Mapper; procedure Set_Variable (Context : in out Default_Context; Name : in String; Value : access Util.Beans.Basic.Readonly_Bean'Class) is use EL.Variables; begin if Context.Var_Mapper = null then Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper; Context.Var_Mapper_Created := True; end if; Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value, EL.Objects.STATIC)); end Set_Variable; -- Handle the exception during expression evaluation. overriding procedure Handle_Exception (Context : in Default_Context; Ex : in Ada.Exceptions.Exception_Occurrence) is begin null; end Handle_Exception; -- ------------------------------ -- Guarded Context -- ------------------------------ -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : in Guarded_Context) return ELResolver_Access is begin return Context.Context.Get_Resolver; end Get_Resolver; -- ------------------------------ -- Retrieves the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : in Guarded_Context) return access EL.Variables.Variable_Mapper'Class is begin return Context.Context.Get_Variable_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the Function_Mapper associated with this ELContext. -- The Function_Mapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : in Guarded_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Context.Get_Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Guarded_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin Context.Context.Set_Function_Mapper (Mapper); end Set_Function_Mapper; -- ------------------------------ -- Set the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Guarded_Context; Mapper : access EL.Variables.Variable_Mapper'Class) is begin Context.Context.Set_Variable_Mapper (Mapper); end Set_Variable_Mapper; -- ------------------------------ -- Handle the exception during expression evaluation. -- ------------------------------ overriding procedure Handle_Exception (Context : in Guarded_Context; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Context.Handler.all (Ex); end Handle_Exception; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Default_ELResolver; Context : ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Object is pragma Unreferenced (Context); Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; declare Pos : constant Objects.Maps.Cursor := Resolver.Map.Find (Key); begin if Objects.Maps.Has_Element (Pos) then return Objects.Maps.Element (Pos); end if; end; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in out Default_ELResolver; Context : in ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Object) is begin null; end Set_Value; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in Util.Beans.Basic.Readonly_Bean_Access) is begin Resolver.Register (Name, To_Object (Value)); end Register; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in EL.Objects.Object) is Key : constant String := To_String (Name); begin Objects.Maps.Include (Resolver.Map, Key, Value); end Register; overriding procedure Finalize (Obj : in out Default_Context) is begin if Obj.Var_Mapper_Created then Free (Obj.Var_Mapper); end if; end Finalize; end EL.Contexts.Default;
----------------------------------------------------------------------- -- EL.Contexts -- Default contexts for evaluating an expression -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with EL.Variables.Default; package body EL.Contexts.Default is use EL.Objects; procedure Free is new Ada.Unchecked_Deallocation (Object => EL.Variables.Variable_Mapper'Class, Name => EL.Variables.Variable_Mapper_Access); -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : Default_Context) return ELResolver_Access is begin return Context.Resolver; end Get_Resolver; -- ------------------------------ -- Set the ELResolver associated with this ELcontext. -- ------------------------------ procedure Set_Resolver (Context : in out Default_Context; Resolver : in ELResolver_Access) is begin Context.Resolver := Resolver; end Set_Resolver; -- ------------------------------ -- Retrieves the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : Default_Context) return access EL.Variables.Variable_Mapper'Class is begin return Context.Var_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the Function_Mapper associated with this ELContext. -- The Function_Mapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : Default_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Default_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin if Mapper = null then Context.Function_Mapper := null; else Context.Function_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Function_Mapper; -- ------------------------------ -- Set the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Default_Context; Mapper : access EL.Variables.Variable_Mapper'Class) is use EL.Variables; begin if Context.Var_Mapper_Created then Free (Context.Var_Mapper); end if; if Mapper = null then Context.Var_Mapper := null; else Context.Var_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Variable_Mapper; procedure Set_Variable (Context : in out Default_Context; Name : in String; Value : access Util.Beans.Basic.Readonly_Bean'Class) is use EL.Variables; begin if Context.Var_Mapper = null then Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper; Context.Var_Mapper_Created := True; end if; Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value, EL.Objects.STATIC)); end Set_Variable; -- Handle the exception during expression evaluation. overriding procedure Handle_Exception (Context : in Default_Context; Ex : in Ada.Exceptions.Exception_Occurrence) is begin null; end Handle_Exception; -- ------------------------------ -- Guarded Context -- ------------------------------ -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : in Guarded_Context) return ELResolver_Access is begin return Context.Context.Get_Resolver; end Get_Resolver; -- ------------------------------ -- Retrieves the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : in Guarded_Context) return access EL.Variables.Variable_Mapper'Class is begin return Context.Context.Get_Variable_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the Function_Mapper associated with this ELContext. -- The Function_Mapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : in Guarded_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Context.Get_Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Guarded_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin Context.Context.Set_Function_Mapper (Mapper); end Set_Function_Mapper; -- ------------------------------ -- Set the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Guarded_Context; Mapper : access EL.Variables.Variable_Mapper'Class) is begin Context.Context.Set_Variable_Mapper (Mapper); end Set_Variable_Mapper; -- ------------------------------ -- Handle the exception during expression evaluation. -- ------------------------------ overriding procedure Handle_Exception (Context : in Guarded_Context; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Context.Handler.all (Ex); end Handle_Exception; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Default_ELResolver; Context : ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Object is pragma Unreferenced (Context); Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; declare Pos : constant Objects.Maps.Cursor := Resolver.Map.Find (Key); begin if Objects.Maps.Has_Element (Pos) then return Objects.Maps.Element (Pos); end if; end; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in out Default_ELResolver; Context : in ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Object) is begin null; end Set_Value; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in Util.Beans.Basic.Readonly_Bean_Access) is begin Resolver.Register (Name, To_Object (Value)); end Register; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in EL.Objects.Object) is Key : constant String := To_String (Name); begin Objects.Maps.Include (Resolver.Map, Key, Value); end Register; overriding procedure Finalize (Obj : in out Default_Context) is begin if Obj.Var_Mapper_Created then Free (Obj.Var_Mapper); end if; end Finalize; end EL.Contexts.Default;
Add use clause for EL.Objects
Add use clause for EL.Objects
Ada
apache-2.0
stcarrez/ada-el
d5388b754932872706152a93a7f1fc7aeb26349e
src/ado-queries.ads
src/ado-queries.ads
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; private with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Named Queries == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application by using named queries. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database. -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by Dynamo to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by Dynamo. -- -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- === SQL Result Mapping === -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify any table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; type Query_Info_Access is access all Query_Info; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.Unbounded_String; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
----------------------------------------------------------------------- -- ado-queries -- Database Queries -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with ADO.SQL; with ADO.Drivers; private with Interfaces; with Ada.Strings.Unbounded; with Ada.Finalization; -- == Named Queries == -- Ada Database Objects provides a small framework which helps in -- using complex SQL queries in an application by using named queries. -- The benefit of the framework are the following: -- -- * The SQL query result are directly mapped in Ada records, -- * It is easy to change or tune an SQL query without re-building the application, -- * The SQL query can be easily tuned for a given database. -- -- The database query framework uses an XML query file: -- -- * The XML query file defines a mapping that represents the result of SQL queries, -- * The XML mapping is used by Dynamo to generate an Ada record, -- * The XML query file also defines a set of SQL queries, each query being identified by a unique name, -- * The XML query file is read by the application to obtain the SQL query associated with a query name, -- * The application uses the `List` procedure generated by Dynamo. -- -- === XML Query File === -- The XML query file uses the `query-mapping` root element. It should -- define at most one `class` mapping and several `query` definitions. -- The `class` definition should come first before any `query` definition. -- -- <query-mapping> -- <class>...</class> -- <query>...</query> -- </query-mapping> -- -- === SQL Result Mapping === -- The XML query mapping is very close to the database table mapping. -- The difference is that there is no need to specify any table name -- nor any SQL type. The XML query mapping is used to build an Ada -- record that correspond to query results. Unlike the database table mapping, -- the Ada record will not be tagged and its definition will expose all the record -- members directly. -- -- The following XML query mapping: -- -- <query-mapping> -- <class name='Samples.Model.User_Info'> -- <property name="name" type="String"> -- <comment>the user name</comment> -- </property> -- <property name="email" type="String"> -- <comment>the email address</comment> -- </property> -- </class> -- </query-mapping> -- -- will generate the following Ada record: -- -- package Samples.Model is -- type User_Info is record -- Name : Unbounded_String; -- Email : Unbounded_String; -- end record; -- end Samples.Model; -- -- The same query mapping can be used by different queries. -- -- === SQL Queries === -- The XML query file defines a list of SQL queries that the application -- can use. Each query is associated with a unique name. The application -- will use that name to identify the SQL query to execute. For each query, -- the file also describes the SQL query pattern that must be used for -- the query execution. -- -- <query name='xxx' class='Samples.Model.User_Info'> -- <sql driver='mysql'> -- select u.name, u.email from user -- </sql> -- <sql driver='sqlite'> -- ... -- </sql> -- <sql-count driver='mysql'> -- select count(*) from user u -- </sql-count> -- </query> -- -- The query contains basically two SQL patterns. The `sql` element represents -- the main SQL pattern. This is the SQL that is used by the `List` operation. -- In some cases, the result set returned by the query is limited to return only -- a maximum number of rows. This is often use in paginated lists. -- -- The `sql-count` element represents an SQL query to indicate the total number -- of elements if the SQL query was not limited. package ADO.Queries is -- Exception raised when a query does not exist or is empty. Query_Error : exception; type Query_Index is new Natural; type File_Index is new Natural; type Query_File is limited private; type Query_File_Access is access all Query_File; type Query_Definition is limited private; type Query_Definition_Access is access all Query_Definition; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with private; type Query_Manager_Access is access all Query_Manager; -- ------------------------------ -- Query Context -- ------------------------------ -- The <b>Context</b> type holds the necessary information to build and execute -- a query whose SQL pattern is defined in an XML query file. type Context is new ADO.SQL.Query with private; -- Set the query definition which identifies the SQL query to execute. -- The query is represented by the <tt>sql</tt> XML entry. procedure Set_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query count definition which identifies the SQL query to execute. -- The query count is represented by the <tt>sql-count</tt> XML entry. procedure Set_Count_Query (Into : in out Context; Query : in Query_Definition_Access); -- Set the query to execute as SQL statement. procedure Set_SQL (Into : in out Context; SQL : in String); procedure Set_Query (Into : in out Context; Name : in String); -- Set the limit for the SQL query. procedure Set_Limit (Into : in out Context; First : in Natural; Last : in Natural); -- Get the first row index. function Get_First_Row_Index (From : in Context) return Natural; -- Get the last row index. function Get_Last_Row_Index (From : in Context) return Natural; -- Get the maximum number of rows that the SQL query can return. -- This operation uses the <b>sql-count</b> query. function Get_Max_Row_Count (From : in Context) return Natural; -- Get the SQL query that correspond to the query context. function Get_SQL (From : in Context; Manager : in Query_Manager'Class) return String; function Get_SQL (From : in Query_Definition_Access; Manager : in Query_Manager; Use_Count : in Boolean) return String; private -- ------------------------------ -- Query Definition -- ------------------------------ -- The <b>Query_Definition</b> holds the SQL query pattern which is defined -- in an XML query file. The query is identified by a name and a given XML -- query file can contain several queries. The Dynamo generator generates -- one instance of <b>Query_Definition</b> for each query defined in the XML -- file. The XML file is loaded during application initialization (or later) -- to get the SQL query pattern. Multi-thread concurrency is achieved by -- the Query_Info_Ref atomic reference. type Query_Definition is limited record -- The query name. Name : Util.Strings.Name_Access; -- The query file in which the query is defined. File : Query_File_Access; -- The next query defined in the query file. Next : Query_Definition_Access; -- The SQL query pattern (initialized when reading the XML query file). -- Query : Query_Info_Ref_Access; Query : Query_Index := 0; end record; -- ------------------------------ -- Query File -- ------------------------------ -- The <b>Query_File</b> describes the SQL queries associated and loaded from -- a given XML query file. The Dynamo generator generates one instance of -- <b>Query_File</b> for each XML query file that it has read. The Path, -- Sha1_Map, Queries and Next are initialized statically by the generator (during -- package elaboration). type Query_File is limited record -- Query relative path name Name : Util.Strings.Name_Access; -- The SHA1 hash of the query map section. Sha1_Map : Util.Strings.Name_Access; -- The first query defined for that file. Queries : Query_Definition_Access; -- The next XML query file registered in the application. Next : Query_File_Access; -- The unique file index. File : File_Index := 0; end record; type Context is new ADO.SQL.Query with record First : Natural := 0; Last : Natural := 0; Last_Index : Natural := 0; Max_Row_Count : Natural := 0; Query_Def : Query_Definition_Access := null; Is_Count : Boolean := False; end record; use Ada.Strings.Unbounded; -- SQL query pattern type Query_Pattern is limited record SQL : Ada.Strings.Unbounded.Unbounded_String; end record; type Query_Pattern_Array is array (ADO.Drivers.Driver_Index) of Query_Pattern; type Query_Info is new Util.Refs.Ref_Entity with record Main_Query : Query_Pattern_Array; Count_Query : Query_Pattern_Array; end record; type Query_Info_Access is access all Query_Info; package Query_Info_Ref is new Util.Refs.References (Query_Info, Query_Info_Access); type Query_Info_Ref_Access is access all Query_Info_Ref.Atomic_Ref; subtype Query_Index_Table is Query_Index range 1 .. Query_Index'Last; subtype File_Index_Table is File_Index range 1 .. File_Index'Last; type Query_File_Info is record -- Query absolute path name (after path resolution). Path : Ada.Strings.Unbounded.Unbounded_String; -- File File : Query_File_Access; -- Stamp when the query file will be checked. Next_Check : Interfaces.Unsigned_32; -- Stamp identifying the modification date of the query file. Last_Modified : Interfaces.Unsigned_32; end record; -- Find the query with the given name. -- Returns the query definition that matches the name or null if there is none function Find_Query (File : in Query_File_Info; Name : in String) return Query_Definition_Access; type Query_Table is array (Query_Index_Table range <>) of Query_Info_Ref.Ref; type Query_Table_Access is access all Query_Table; type File_Table is array (File_Index_Table range <>) of Query_File_Info; type File_Table_Access is access all File_Table; type Query_Manager is limited new Ada.Finalization.Limited_Controlled with record Driver : ADO.Drivers.Driver_Index; Queries : Query_Table_Access; Files : File_Table_Access; end record; overriding procedure Finalize (Manager : in out Query_Manager); end ADO.Queries;
Declare the Query_Error exception
Declare the Query_Error exception
Ada
apache-2.0
stcarrez/ada-ado
709e2f4d23d5c6a10c48195f778e752712f326f6
src/asf-components-util-factory.adb
src/asf-components-util-factory.adb
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Html.Text; with ASF.Components.Html.Lists; with ASF.Components.Core; with ASF.Views.Nodes; with Util.Strings.Escapes; use Util.Strings; with EL.Functions.Default; package body ASF.Components.Util.Factory is function Create_View return UIComponent_Access; function Create_Parameter return UIComponent_Access; -- ------------------------------ -- Create an UIView component -- ------------------------------ function Create_View return UIComponent_Access is begin return new ASF.Components.Core.UIView; end Create_View; -- ------------------------------ -- Create an UIParameter component -- ------------------------------ function Create_Parameter return UIComponent_Access is begin return new ASF.Components.Core.UIParameter; end Create_Parameter; use ASF.Views.Nodes; URI : aliased constant String := "http://code.google.com/p/ada-asf/util"; VIEW_TAG : aliased constant String := "view"; PARAM_TAG : aliased constant String := "param"; LIST_TAG : aliased constant String := "list"; Core_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => PARAM_TAG'Access, Component => Create_Parameter'Access, Tag => Create_Component_Node'Access), 2 => (Name => VIEW_TAG'Access, Component => Create_View'Access, Tag => Create_Component_Node'Access) ); Core_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Core_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Core_Factory'Access; end Definition; -- Truncate the string representation represented by <b>Value</b> to -- the length specified by <b>Size</b>. function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "escapeJavaScript", Namespace => URI, Func => Escape_Javascript'Access); end Set_Functions; function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Escapes.Escape_Javascript (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Javascript; begin ASF.Factory.Check (Core_Factory); end ASF.Components.Util.Factory;
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Core; with ASF.Views.Nodes; with Util.Strings.Transforms; use Util.Strings; with EL.Functions.Default; package body ASF.Components.Util.Factory is function Create_View return UIComponent_Access; function Create_Parameter return UIComponent_Access; -- ------------------------------ -- Create an UIView component -- ------------------------------ function Create_View return UIComponent_Access is begin return new ASF.Components.Core.UIView; end Create_View; -- ------------------------------ -- Create an UIParameter component -- ------------------------------ function Create_Parameter return UIComponent_Access is begin return new ASF.Components.Core.UIParameter; end Create_Parameter; use ASF.Views.Nodes; URI : aliased constant String := "http://code.google.com/p/ada-asf/util"; VIEW_TAG : aliased constant String := "view"; PARAM_TAG : aliased constant String := "param"; LIST_TAG : aliased constant String := "list"; Core_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => PARAM_TAG'Access, Component => Create_Parameter'Access, Tag => Create_Component_Node'Access), 2 => (Name => VIEW_TAG'Access, Component => Create_View'Access, Tag => Create_Component_Node'Access) ); Core_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Core_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Core_Factory'Access; end Definition; -- Truncate the string representation represented by <b>Value</b> to -- the length specified by <b>Size</b>. function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object; -- Escape the string using XML escape rules. function Escape_Xml (Value : EL.Objects.Object) return EL.Objects.Object; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "escapeJavaScript", Namespace => URI, Func => Escape_Javascript'Access); Mapper.Set_Function (Name => "escapeXml", Namespace => URI, Func => Escape_Xml'Access); end Set_Functions; function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Transforms.Escape_Javascript (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Javascript; function Escape_Xml (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Transforms.Escape_Xml (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Xml; begin ASF.Factory.Check (Core_Factory); end ASF.Components.Util.Factory;
Add escapeXml function
Add escapeXml function
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b813060578d166cdad45f23eea3ea698f72872a9
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "04"; copyright_years : constant String := "2015-2018"; 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.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.2.0"; previous_compiler : constant String := "7.3.0"; binutils_version : constant String := "2.31.1"; previous_binutils : constant String := "2.30"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 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-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "05"; copyright_years : constant String := "2015-2018"; 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.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.2.0"; previous_compiler : constant String := "7.3.0"; binutils_version : constant String := "2.31.1"; previous_binutils : constant String := "2.30"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 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-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Bump for next release
Bump for next release Minor, no corresponding bump for Ravenports
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
6c4e4d7ee4a7a507e75d0201b7a09b563209e426
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 := "90"; copyright_years : constant String := "2015-2018"; 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.26"; default_pgsql : constant String := "9.6"; default_php : constant String := "7.1"; default_python3 : constant String := "3.6"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc7"; compiler_version : constant String := "7.2.0"; previous_compiler : constant String := "7.1.0"; binutils_version : constant String := "2.29.1"; previous_binutils : constant String := "2.29"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 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-static"; 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 := "91"; copyright_years : constant String := "2015-2018"; 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.26"; default_pgsql : constant String := "9.6"; default_php : constant String := "7.1"; default_python3 : constant String := "3.6"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc7"; compiler_version : constant String := "7.3.0"; previous_compiler : constant String := "7.2.0"; binutils_version : constant String := "2.30"; previous_binutils : constant String := "2.29.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 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-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Prepare for gcc and binutil upgrades
Prepare for gcc and binutil upgrades
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
1d193bc1ef99c8103ded0358f19beb1b2d46ed90
src/orka/implementation/orka-transforms-simd_quaternions.adb
src/orka/implementation/orka-transforms-simd_quaternions.adb
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with Orka.SIMD; package body Orka.Transforms.SIMD_Quaternions is package EF is new Ada.Numerics.Generic_Elementary_Functions (Vectors.Element_Type); function Vector_Part (Elements : Quaternion) return Vector4 is begin return Result : Vector4 := Vector4 (Elements) do Result (SIMD.W) := 0.0; end return; end Vector_Part; function "*" (Left, Right : Quaternion) return Quaternion is use Vectors; Lv : constant Vector4 := Vector_Part (Left); Rv : constant Vector4 := Vector_Part (Right); Ls : constant Vectors.Element_Type := Left (SIMD.W); Rs : constant Vectors.Element_Type := Right (SIMD.W); V : constant Vector4 := Ls * Rv + Rs * Lv + Vectors.Cross (Lv, Rv); S : constant Element_Type := Ls * Rs - Vectors.Dot (Lv, Rv); begin return Result : Quaternion := Quaternion (V) do Result (SIMD.W) := S; end return; end "*"; function Conjugate (Elements : Quaternion) return Quaternion is W : constant Vectors.Element_Type := Elements (SIMD.W); use Vectors; begin return Result : Quaternion := Quaternion (-Vector4 (Elements)) do Result (SIMD.W) := W; end return; end Conjugate; function Norm (Elements : Quaternion) return Vectors.Element_Type is (Vectors.Magnitude (Vector4 (Elements))); function Normalize (Elements : Quaternion) return Quaternion is (Quaternion (Vectors.Normalize (Vector4 (Elements)))); function Normalized (Elements : Quaternion) return Boolean is (Vectors.Normalized (Vector4 (Elements))); function R (Axis : Vector4; Angle : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; CA : constant Vectors.Element_Type := EF.Cos (Angle / 2.0, 360.0); SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0, 360.0); use Vectors; begin return Result : Quaternion := Quaternion (Axis * SA) do Result (SIMD.W) := CA; end return; end R; function R (Left, Right : Vector4) return Quaternion is use type Vectors.Element_Type; S : constant Vector4 := Vectors.Normalize (Left); T : constant Vector4 := Vectors.Normalize (Right); E : constant Vectors.Element_Type := Vectors.Dot (S, T); SRE : constant Vectors.Element_Type := EF.Sqrt (2.0 * (1.0 + E)); use Vectors; begin -- Division by zero if Left and Right are in opposite direction. -- Use rotation axis perpendicular to s and angle of 180 degrees if SRE /= 0.0 then -- Equation 4.53 from chapter 4.3 Quaternions from Real-Time Rendering -- (third edition, 2008) declare Result : Quaternion := Quaternion ((1.0 / SRE) * Vectors.Cross (S, T)); begin Result (SIMD.W) := SRE / 2.0; return Normalize (Result); end; else if abs S (SIMD.Z) < abs S (SIMD.X) then return R ((S (SIMD.Y), -S (SIMD.X), 0.0, 0.0), 180.0); else return R ((0.0, -S (SIMD.Z), S (SIMD.Y), 0.0), 180.0); end if; end if; end R; function Difference (Left, Right : Quaternion) return Quaternion is begin return Right * Conjugate (Left); end Difference; procedure Rotate_At_Origin (Vector : in out Vector4; Elements : Quaternion) is begin Vector := Vectors.Vector_Type (Elements * Quaternion (Vector) * Conjugate (Elements)); end Rotate_At_Origin; function Lerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; use Vectors; begin return Normalize (Quaternion ((1.0 - Time) * Vector4 (Left) + Time * Vector4 (Right))); end Lerp; function Slerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; Cos_Angle : constant Vectors.Element_Type := Vectors.Dot (Vector4 (Left), Vector4 (Right)); Angle : constant Vectors.Element_Type := EF.Arccos (Cos_Angle, 360.0); SA : constant Vectors.Element_Type := EF.Sin (Angle, 360.0); SL : constant Vectors.Element_Type := EF.Sin ((1.0 - Time) * Angle, 360.0); SR : constant Vectors.Element_Type := EF.Sin (Time * Angle, 360.0); use Vectors; begin return Quaternion ((SL / SA) * Vector4 (Left) + (SR / SA) * Vector4 (Right)); end Slerp; function Image (Elements : Quaternion) return String is (Vectors.Image (Vectors.Vector_Type (Elements))); end Orka.Transforms.SIMD_Quaternions;
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with Orka.SIMD; package body Orka.Transforms.SIMD_Quaternions is package EF is new Ada.Numerics.Generic_Elementary_Functions (Vectors.Element_Type); function Vector_Part (Elements : Quaternion) return Vector4 is begin return Result : Vector4 := Vector4 (Elements) do Result (SIMD.W) := 0.0; end return; end Vector_Part; function "*" (Left, Right : Quaternion) return Quaternion is use Vectors; Lv : constant Vector4 := Vector_Part (Left); Rv : constant Vector4 := Vector_Part (Right); Ls : constant Vectors.Element_Type := Left (SIMD.W); Rs : constant Vectors.Element_Type := Right (SIMD.W); V : constant Vector4 := Ls * Rv + Rs * Lv + Vectors.Cross (Lv, Rv); S : constant Element_Type := Ls * Rs - Vectors.Dot (Lv, Rv); begin return Result : Quaternion := Quaternion (V) do Result (SIMD.W) := S; end return; end "*"; function Conjugate (Elements : Quaternion) return Quaternion is W : constant Vectors.Element_Type := Elements (SIMD.W); use Vectors; begin return Result : Quaternion := Quaternion (-Vector4 (Elements)) do Result (SIMD.W) := W; end return; end Conjugate; function Norm (Elements : Quaternion) return Vectors.Element_Type is (Vectors.Magnitude (Vector4 (Elements))); function Normalize (Elements : Quaternion) return Quaternion is (Quaternion (Vectors.Normalize (Vector4 (Elements)))); function Normalized (Elements : Quaternion) return Boolean is (Vectors.Normalized (Vector4 (Elements))); function R (Axis : Vector4; Angle : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; CA : constant Vectors.Element_Type := EF.Cos (Angle / 2.0, 360.0); SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0, 360.0); use Vectors; begin return Result : Quaternion := Quaternion (Axis * SA) do Result (SIMD.W) := CA; end return; end R; function R (Left, Right : Vector4) return Quaternion is use type Vectors.Element_Type; S : constant Vector4 := Vectors.Normalize (Left); T : constant Vector4 := Vectors.Normalize (Right); E : constant Vectors.Element_Type := Vectors.Dot (S, T); SRE : constant Vectors.Element_Type := EF.Sqrt (2.0 * (1.0 + E)); use Vectors; begin -- Division by zero if Left and Right are in opposite direction. -- Use rotation axis perpendicular to s and angle of 180 degrees if SRE /= 0.0 then -- Equation 4.53 from chapter 4.3 Quaternions from Real-Time Rendering -- (third edition, 2008) declare Result : Quaternion := Quaternion ((1.0 / SRE) * Vectors.Cross (S, T)); begin Result (SIMD.W) := SRE / 2.0; return Normalize (Result); end; else if abs S (SIMD.Z) < abs S (SIMD.X) then return R ((S (SIMD.Y), -S (SIMD.X), 0.0, 0.0), 180.0); else return R ((0.0, -S (SIMD.Z), S (SIMD.Y), 0.0), 180.0); end if; end if; end R; function Difference (Left, Right : Quaternion) return Quaternion is begin return Right * Conjugate (Left); end Difference; procedure Rotate_At_Origin (Vector : in out Vector4; Elements : Quaternion) is Result : Vectors.Vector_Type; begin Result := Vectors.Vector_Type (Elements * Quaternion (Vector) * Conjugate (Elements)); Vector := Result; end Rotate_At_Origin; function Lerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; use Vectors; begin return Normalize (Quaternion ((1.0 - Time) * Vector4 (Left) + Time * Vector4 (Right))); end Lerp; function Slerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; Cos_Angle : constant Vectors.Element_Type := Vectors.Dot (Vector4 (Left), Vector4 (Right)); Angle : constant Vectors.Element_Type := EF.Arccos (Cos_Angle, 360.0); SA : constant Vectors.Element_Type := EF.Sin (Angle, 360.0); SL : constant Vectors.Element_Type := EF.Sin ((1.0 - Time) * Angle, 360.0); SR : constant Vectors.Element_Type := EF.Sin (Time * Angle, 360.0); use Vectors; begin return Quaternion ((SL / SA) * Vector4 (Left) + (SR / SA) * Vector4 (Right)); end Slerp; function Image (Elements : Quaternion) return String is (Vectors.Image (Vectors.Vector_Type (Elements))); end Orka.Transforms.SIMD_Quaternions;
Modify procedure Rotate_At_Origin to fix some failing unit tests
orka: Modify procedure Rotate_At_Origin to fix some failing unit tests Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
eeafa4441ffd8b88ecaaea99c2192f34c15a9363
awa/plugins/awa-setup/src/awa-setup-applications.adb
awa/plugins/awa-setup/src/awa-setup-applications.adb
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- 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.Text_IO; with Ada.IO_Exceptions; with Util.Files; with Util.Log.Loggers; with Util.Strings; with ASF.Events.Faces.Actions; with ASF.Applications.Main.Configs; with AWA.Applications; package body AWA.Setup.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications"); package Save_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Save, Name => "save"); package Finish_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Finish, Name => "finish"); package Configure_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Configure_Database, Name => "configure_database"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Finish_Binding.Proxy'Access, Configure_Binding.Proxy'Access); -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object is begin if Name = "database_name" then return Util.Beans.Objects.To_Object (From.Database.Get_Database); elsif Name = "database_server" then return Util.Beans.Objects.To_Object (From.Database.Get_Server); elsif Name = "database_port" then return Util.Beans.Objects.To_Object (From.Database.Get_Port); elsif Name = "database_user" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user")); elsif Name = "database_password" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password")); end if; if From.Changed.Exists (Name) then return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name))); end if; declare Param : constant String := From.Config.Get (Name); begin return Util.Beans.Objects.To_Object (Param); end; exception when others => return Util.Beans.Objects.Null_Object; end Get_Value; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "database_name" then From.Database.Set_Database (Util.Beans.Objects.To_String (Value)); elsif Name = "database_server" then From.Database.Set_Server (Util.Beans.Objects.To_String (Value)); elsif Name = "database_port" then From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value)); elsif Name = "database_user" then From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value)); elsif Name = "database_password" then From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value)); elsif Name = "callback_url" then From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); From.Changed.Set ("facebook.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); From.Changed.Set ("google-plus.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); else From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Configure database"); end Configure_Database; -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Path : constant String := Ada.Strings.Unbounded.To_String (From.Path); New_File : constant String := Path & ".tmp"; Output : Ada.Text_IO.File_Type; procedure Read_Property (Line : in String) is Pos : constant Natural := Util.Strings.Index (Line, '='); begin if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then Ada.Text_IO.Put_Line (Output, Line); return; end if; Ada.Text_IO.Put (Output, Line (Line'First .. Pos)); Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1))); end Read_Property; begin Log.Info ("Saving configuration file {0}", Path); Ada.Text_IO.Create (File => Output, Name => New_File); Util.Files.Read_File (Path, Read_Property'Access); Ada.Text_IO.Close (Output); end Save; -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Finish configuration"); From.Done := True; end Finish; -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class) is begin Log.Info ("Entering configuration for {0}", Config); App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config); begin App.Config.Load_Properties (Config); Util.Log.Loggers.Initialize (Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file: {0}", Config); end; App.Initialize (App.Config, App.Factory); App.Set_Global ("contextPath", App.Config.Get ("contextPath")); App.Set_Global ("setup", Util.Beans.Objects.To_Object (App'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Mapping (Pattern => "*.html", Name => "faces"); App.Add_Mapping (Pattern => "*.css", Name => "files"); App.Add_Mapping (Pattern => "*.js", Name => "files"); declare Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P); Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths); begin ASF.Applications.Main.Configs.Read_Configuration (App, Path); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Setup configuration file '{0}' does not exist", Path); end; declare URL : constant String := App.Config.Get ("google-plus.callback_url", ""); Pos : Natural := Util.Strings.Index (URL, '#'); begin if Pos > 0 then App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1)); end if; end; App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db")); Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access); Server.Start; while not App.Done loop delay 5.0; end loop; end Setup; end AWA.Setup.Applications;
----------------------------------------------------------------------- -- awa-setup -- Setup and installation -- 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.Text_IO; with Ada.IO_Exceptions; with Util.Files; with Util.Log.Loggers; with Util.Strings; with ASF.Events.Faces.Actions; with ASF.Applications.Main.Configs; with AWA.Applications; package body AWA.Setup.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Setup.Applications"); package Save_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Save, Name => "save"); package Finish_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Finish, Name => "finish"); package Configure_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Application, Method => Configure_Database, Name => "configure_database"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Save_Binding.Proxy'Access, Finish_Binding.Proxy'Access, Configure_Binding.Proxy'Access); -- Get the value identified by the name. function Get_Value (From : in Application; Name : in String) return Util.Beans.Objects.Object is begin if Name = "database_name" then return Util.Beans.Objects.To_Object (From.Database.Get_Database); elsif Name = "database_server" then return Util.Beans.Objects.To_Object (From.Database.Get_Server); elsif Name = "database_port" then return Util.Beans.Objects.To_Object (From.Database.Get_Port); elsif Name = "database_user" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("user")); elsif Name = "database_password" then return Util.Beans.Objects.To_Object (From.Database.Get_Property ("password")); end if; if From.Changed.Exists (Name) then return Util.Beans.Objects.To_Object (String '(From.Changed.Get (Name))); end if; declare Param : constant String := From.Config.Get (Name); begin return Util.Beans.Objects.To_Object (Param); end; exception when others => return Util.Beans.Objects.Null_Object; end Get_Value; -- Set the value identified by the name. procedure Set_Value (From : in out Application; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "database_name" then From.Database.Set_Database (Util.Beans.Objects.To_String (Value)); elsif Name = "database_server" then From.Database.Set_Server (Util.Beans.Objects.To_String (Value)); elsif Name = "database_port" then From.Database.Set_Port (Util.Beans.Objects.To_Integer (Value)); elsif Name = "database_user" then From.Database.Set_Property ("user", Util.Beans.Objects.To_String (Value)); elsif Name = "database_password" then From.Database.Set_Property ("password", Util.Beans.Objects.To_String (Value)); elsif Name = "callback_url" then From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); From.Changed.Set ("facebook.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); From.Changed.Set ("google-plus.callback_url", Util.Beans.Objects.To_String (Value) & "#{contextPath}/auth/verify"); else From.Changed.Set (Name, Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Get the database connection string to be used by the application. -- ------------------------------ function Get_Database_URL (From : in Application) return String is use Ada.Strings.Unbounded; Result : Ada.Strings.Unbounded.Unbounded_String; begin Append (Result, "mysql://"); Append (Result, From.Database.Get_Server); if From.Database.Get_Port /= 0 then Append (Result, ":"); Append (Result, Util.Strings.Image (From.Database.Get_Port)); end if; Append (Result, "/"); Append (Result, From.Database.Get_Database); if From.Database.Get_Property ("user") /= "" then Append (Result, "?user="); Append (Result, From.Database.Get_Property ("user")); if From.Database.Get_Property ("password") /= "" then Append (Result, "&password="); Append (Result, From.Database.Get_Property ("password")); end if; end if; return To_String (Result); end Get_Database_URL; -- Configure the database. procedure Configure_Database (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Configure database"); end Configure_Database; -- Save the configuration. procedure Save (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Path : constant String := Ada.Strings.Unbounded.To_String (From.Path); New_File : constant String := Path & ".tmp"; Output : Ada.Text_IO.File_Type; procedure Read_Property (Line : in String) is Pos : constant Natural := Util.Strings.Index (Line, '='); begin if Pos = 0 or else not From.Changed.Exists (Line (Line'First .. Pos - 1)) then Ada.Text_IO.Put_Line (Output, Line); return; end if; Ada.Text_IO.Put (Output, Line (Line'First .. Pos)); Ada.Text_IO.Put_Line (Output, From.Changed.Get (Line (Line'First .. Pos - 1))); end Read_Property; begin Log.Info ("Saving configuration file {0}", Path); Ada.Text_IO.Create (File => Output, Name => New_File); Util.Files.Read_File (Path, Read_Property'Access); Ada.Text_IO.Close (Output); end Save; -- Finish the setup and exit the setup. procedure Finish (From : in out Application; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Log.Info ("Finish configuration"); From.Done := True; end Finish; -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Application) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; -- Enter in the application setup procedure Setup (App : in out Application; Config : in String; Server : in out ASF.Server.Container'Class) is begin Log.Info ("Entering configuration for {0}", Config); App.Path := Ada.Strings.Unbounded.To_Unbounded_String (Config); begin App.Config.Load_Properties (Config); Util.Log.Loggers.Initialize (Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read application configuration file: {0}", Config); end; App.Initialize (App.Config, App.Factory); App.Set_Global ("contextPath", App.Config.Get ("contextPath")); App.Set_Global ("setup", Util.Beans.Objects.To_Object (App'Unchecked_Access, Util.Beans.Objects.STATIC)); App.Add_Servlet (Name => "faces", Server => App.Faces'Unchecked_Access); App.Add_Servlet (Name => "files", Server => App.Files'Unchecked_Access); App.Add_Mapping (Pattern => "*.html", Name => "faces"); App.Add_Mapping (Pattern => "*.css", Name => "files"); App.Add_Mapping (Pattern => "*.js", Name => "files"); declare Paths : constant String := App.Get_Config (AWA.Applications.P_Module_Dir.P); Path : constant String := Util.Files.Find_File_Path ("setup.xml", Paths); begin ASF.Applications.Main.Configs.Read_Configuration (App, Path); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Setup configuration file '{0}' does not exist", Path); end; declare URL : constant String := App.Config.Get ("google-plus.callback_url", ""); Pos : Natural := Util.Strings.Index (URL, '#'); begin if Pos > 0 then App.Changed.Set ("callback_url", URL (URL'First .. Pos - 1)); end if; end; App.Database.Set_Connection (App.Config.Get ("database", "mysql://localhost:3306/db")); Server.Register_Application (App.Config.Get ("contextPath"), App'Unchecked_Access); Server.Start; while not App.Done loop delay 5.0; end loop; end Setup; end AWA.Setup.Applications;
Implement the Get_Database_URL function
Implement the Get_Database_URL function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
70dd1e8c2c7291534bb120737c95a52164a9448c
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
awa/plugins/awa-tags/regtests/awa-tags-modules-tests.adb
----------------------------------------------------------------------- -- awa-tags-modules-tests -- Unit tests for tags module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tags.Beans; package body AWA.Tags.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Tags.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag", Test_Add_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag", Test_Remove_Tag'Access); end Add_Tests; function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access is Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module); begin return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Test tag creation. -- ------------------------------ procedure Test_Add_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); -- Create a tag. Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Add_Tag; -- ------------------------------ -- Test tag removal. -- ------------------------------ procedure Test_Remove_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 2, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Remove_Tag; end AWA.Tags.Modules.Tests;
----------------------------------------------------------------------- -- awa-tags-modules-tests -- Unit tests for tags module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Tags.Beans; package body AWA.Tags.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Tags.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag", Test_Add_Tag'Access); Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag", Test_Remove_Tag'Access); end Add_Tests; function Create_Tag_List_Bean (Module : in Tag_Module_Access) return AWA.Tags.Beans.Tag_List_Bean_Access is Bean : Util.Beans.Basic.Readonly_Bean_Access := AWA.Tags.Beans.Create_Tag_List_Bean (Module); begin return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access; end Create_Tag_List_Bean; -- ------------------------------ -- Test tag creation. -- ------------------------------ procedure Test_Add_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); -- Create a tag. Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Add_Tag; -- ------------------------------ -- Test tag removal. -- ------------------------------ procedure Test_Remove_Tag (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Tag_Manager : constant Tag_Module_Access := Get_Tag_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; List : AWA.Tags.Beans.Tag_List_Bean_Access; Cleanup : Util.Beans.Objects.Object; begin T.Assert (Tag_Manager /= null, "There is no tag module"); List := Create_Tag_List_Bean (Tag_Manager); Cleanup := Util.Beans.Objects.To_Object (List.all'Access); List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user"))); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2"); Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1"); -- Load the list. List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id); Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags"); end; end Test_Remove_Tag; end AWA.Tags.Modules.Tests;
Fix the tags unit test
Fix the tags unit test
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
43d4b4a6403b1f696a4fa03c76f114b7adc422b6
awa/src/awa-events-dispatchers-actions.adb
awa/src/awa-events-dispatchers-actions.adb
----------------------------------------------------------------------- -- awa-events-dispatchers-actions -- Event dispatcher to Ada bean actions -- 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 Ada.Exceptions; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with ASF.Beans; with ASF.Requests; with ASF.Sessions; with AWA.Events.Action_Method; package body AWA.Events.Dispatchers.Actions is use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Actions"); -- ------------------------------ -- Dispatch the event identified by <b>Event</b>. -- The event actions which are associated with the event are executed synchronously. -- ------------------------------ procedure Dispatch (Manager : in Action_Dispatcher; Event : in Module_Event'Class) is use Util.Beans.Objects; -- Dispatch the event to the event action identified by <b>Action</b>. procedure Dispatch_One (Action : in Event_Action); type Event_Bean is new Util.Beans.Basic.Readonly_Bean with null record; overriding function Get_Value (From : in Event_Bean; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- 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 Event_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); begin return Event.Get_Value (Name); end Get_Value; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; -- ------------------------------ -- Default Resolver -- ------------------------------ type Event_ELResolver is limited new EL.Contexts.ELResolver with record Request : ASF.Requests.Request_Access; Application : AWA.Applications.Application_Access; end record; overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object; overriding procedure Set_Value (Resolver : in out Event_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object is use Util.Beans.Basic; use EL.Variables; use type ASF.Requests.Request_Access; Result : Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; if Resolver.Request /= null then Result := Resolver.Request.Get_Attribute (Key); if not Util.Beans.Objects.Is_Null (Result) then return Result; end if; -- If there is a session, look if the attribute is defined there. declare Session : constant ASF.Sessions.Session := Resolver.Request.Get_Session; begin if Session.Is_Valid then Result := Session.Get_Attribute (Key); if not Util.Beans.Objects.Is_Null (Result) then return Result; end if; end if; end; end if; Resolver.Application.Create (Name, Context, Bean, Scope); if Bean = null then return Resolver.Application.Get_Global (Name, Context); end if; Result := To_Object (Bean); if Resolver.Request /= null then Resolver.Request.Set_Attribute (Key, Result); else Variables.Bind (Key, Result); end if; return Result; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in out Event_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Context); use type ASF.Requests.Request_Access; Key : constant String := To_String (Name); begin if Base /= null then Base.Set_Value (Name => Key, Value => Value); elsif Resolver.Request /= null then Resolver.Request.Set_Attribute (Name => Key, Value => Value); else Variables.Bind (To_String (Name), Value); end if; end Set_Value; Local_Event : aliased Event_Bean; Resolver : aliased Event_ELResolver; ELContext : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Dispatch the event to the event action identified by <b>Action</b>. -- ------------------------------ procedure Dispatch_One (Action : in Event_Action) is use Ada.Exceptions; Method : EL.Expressions.Method_Info; begin Method := Action.Action.Get_Method_Info (Context => ELContext); if Method.Object.all in Util.Beans.Basic.Bean'Class then -- If we have a prepare method and the bean provides a Set_Value method, -- call the preparation method to fill the bean with some values. EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Method.Object.all), Action.Properties, ELContext); end if; -- Execute the specified method on the bean and give it the event object. AWA.Events.Action_Method.Execute (Method => Method, Param => Event); -- If an exception is raised by the action, do not propagate it: -- o We have to dispatch the event to other actions. -- o The event may be dispatched asynchronously and there is no handler -- that could handle such exception exception when E : others => Log.Error ("Error when executing event action {0}: {1}: {2}", Action.Action.Get_Expression, Exception_Name (E), Exception_Message (E)); end Dispatch_One; Pos : Event_Action_Lists.Cursor := Manager.Actions.First; begin Resolver.Application := Manager.Application; ELContext.Set_Resolver (Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Variables.Bind (Name => "event", Value => To_Object (Local_Event'Unchecked_Access, STATIC)); while Event_Action_Lists.Has_Element (Pos) loop Event_Action_Lists.Query_Element (Pos, Dispatch_One'Access); Event_Action_Lists.Next (Pos); end loop; end Dispatch; -- ------------------------------ -- Add an action invoked when an event is dispatched through this dispatcher. -- When the event queue dispatches the event, the Ada bean identified by the method action -- represented by <b>Action</b> is created and initialized by evaluating and setting the -- parameters defined in <b>Params</b>. The action method is then invoked. -- ------------------------------ procedure Add_Action (Manager : in out Action_Dispatcher; Action : in EL.Expressions.Method_Expression; Params : in EL.Beans.Param_Vectors.Vector) is Item : Event_Action; begin Item.Action := Action; Item.Properties := Params; Manager.Actions.Append (Item); end Add_Action; -- ------------------------------ -- Create a new dispatcher associated with the application. -- ------------------------------ function Create_Dispatcher (Application : in AWA.Applications.Application_Access) return Dispatcher_Access is Result : constant Dispatcher_Access := new Action_Dispatcher '(Dispatcher with Application => Application, others => <>); begin return Result.all'Access; end Create_Dispatcher; end AWA.Events.Dispatchers.Actions;
----------------------------------------------------------------------- -- awa-events-dispatchers-actions -- Event dispatcher to Ada bean actions -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Exceptions; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Contexts; with EL.Contexts.TLS; with EL.Variables; with EL.Variables.Default; with ASF.Beans; with ASF.Requests; with ASF.Sessions; with AWA.Events.Action_Method; package body AWA.Events.Dispatchers.Actions is use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Dispatchers.Actions"); -- ------------------------------ -- Dispatch the event identified by <b>Event</b>. -- The event actions which are associated with the event are executed synchronously. -- ------------------------------ procedure Dispatch (Manager : in Action_Dispatcher; Event : in Module_Event'Class) is use Util.Beans.Objects; -- Dispatch the event to the event action identified by <b>Action</b>. procedure Dispatch_One (Action : in Event_Action); type Event_Bean is new Util.Beans.Basic.Readonly_Bean with null record; overriding function Get_Value (From : in Event_Bean; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- 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 Event_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); begin return Event.Get_Value (Name); end Get_Value; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; -- ------------------------------ -- Default Resolver -- ------------------------------ type Event_ELResolver is limited new EL.Contexts.ELResolver with record Request : ASF.Requests.Request_Access; Application : AWA.Applications.Application_Access; end record; overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object; overriding procedure Set_Value (Resolver : in out Event_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Event_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Util.Beans.Objects.Object is use Util.Beans.Basic; use EL.Variables; use type ASF.Requests.Request_Access; Result : Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; if Resolver.Request /= null then Result := Resolver.Request.Get_Attribute (Key); if not Util.Beans.Objects.Is_Null (Result) then return Result; end if; -- If there is a session, look if the attribute is defined there. declare Session : constant ASF.Sessions.Session := Resolver.Request.Get_Session; begin if Session.Is_Valid then Result := Session.Get_Attribute (Key); if not Util.Beans.Objects.Is_Null (Result) then return Result; end if; end if; end; end if; Resolver.Application.Create (Name, Context, Bean, Scope); if Bean = null then return Resolver.Application.Get_Global (Name, Context); end if; Result := To_Object (Bean); if Resolver.Request /= null then Resolver.Request.Set_Attribute (Key, Result); else Variables.Bind (Key, Result); end if; return Result; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in out Event_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Context); use type ASF.Requests.Request_Access; Key : constant String := To_String (Name); begin if Base /= null then Base.Set_Value (Name => Key, Value => Value); elsif Resolver.Request /= null then Resolver.Request.Set_Attribute (Name => Key, Value => Value); else Variables.Bind (To_String (Name), Value); end if; end Set_Value; Local_Event : aliased Event_Bean; Resolver : aliased Event_ELResolver; ELContext : aliased EL.Contexts.TLS.TLS_Context; -- ------------------------------ -- Dispatch the event to the event action identified by <b>Action</b>. -- ------------------------------ procedure Dispatch_One (Action : in Event_Action) is use Ada.Exceptions; Method : EL.Expressions.Method_Info; begin Method := Action.Action.Get_Method_Info (Context => ELContext); if Method.Object.all in Util.Beans.Basic.Bean'Class then -- If we have a prepare method and the bean provides a Set_Value method, -- call the preparation method to fill the bean with some values. EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Method.Object.all), Action.Properties, ELContext); end if; -- Execute the specified method on the bean and give it the event object. AWA.Events.Action_Method.Execute (Method => Method, Param => Event); -- If an exception is raised by the action, do not propagate it: -- o We have to dispatch the event to other actions. -- o The event may be dispatched asynchronously and there is no handler -- that could handle such exception exception when E : others => Log.Error ("Error when executing event action {0}: {1}: {2}", Action.Action.Get_Expression, Exception_Name (E), Exception_Message (E)); end Dispatch_One; Pos : Event_Action_Lists.Cursor := Manager.Actions.First; begin Resolver.Application := Manager.Application; ELContext.Set_Resolver (Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Variables.Bind (Name => "event", Value => To_Object (Local_Event'Unchecked_Access, STATIC)); while Event_Action_Lists.Has_Element (Pos) loop Event_Action_Lists.Query_Element (Pos, Dispatch_One'Access); Event_Action_Lists.Next (Pos); end loop; end Dispatch; -- ------------------------------ -- Add an action invoked when an event is dispatched through this dispatcher. -- When the event queue dispatches the event, the Ada bean identified by the method action -- represented by <b>Action</b> is created and initialized by evaluating and setting the -- parameters defined in <b>Params</b>. The action method is then invoked. -- ------------------------------ procedure Add_Action (Manager : in out Action_Dispatcher; Action : in EL.Expressions.Method_Expression; Params : in EL.Beans.Param_Vectors.Vector) is Item : Event_Action; begin Item.Action := Action; Item.Properties := Params; Manager.Actions.Append (Item); end Add_Action; -- ------------------------------ -- Create a new dispatcher associated with the application. -- ------------------------------ function Create_Dispatcher (Application : in AWA.Applications.Application_Access) return Dispatcher_Access is Result : constant Dispatcher_Access := new Action_Dispatcher '(Dispatcher with Application => Application, others => <>); begin return Result.all'Access; end Create_Dispatcher; end AWA.Events.Dispatchers.Actions;
Use a thread local EL context when an event action is executed. This allows the action handler to use the same EL context easily.
Use a thread local EL context when an event action is executed. This allows the action handler to use the same EL context easily.
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ea4dd9f87719743362a2abfacd4abd89ef217cf7
src/gen-commands-page.ads
src/gen-commands-page.ads
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- Copyright (C) 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Page is -- ------------------------------ -- Page Creation Command -- ------------------------------ -- This command adds a XHTML page to the web application. type Command is new Gen.Commands.Command with null record; -- 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); -- Write the help associated with the command. overriding procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Page;
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- Copyright (C) 2011, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Page is -- ------------------------------ -- Page Creation Command -- ------------------------------ -- This command adds a XHTML page to the web application. type Command is new Gen.Commands.Command with null record; -- 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); -- Write the help associated with the command. overriding procedure Help (Cmd : in out Command; Name : in String; Generator : in out Gen.Generator.Handler); end Gen.Commands.Page;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
3803bce6bbe35e1f97046fae5d5a7f52c4f8b088
samples/volume_server.adb
samples/volume_server.adb
----------------------------------------------------------------------- -- volume_server -- Example of server with a servlet -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Server.Web; with ASF.Servlets; with Volume_Servlet; procedure Volume_Server is Compute : aliased Volume_Servlet.Servlet; App : aliased ASF.Servlets.Servlet_Registry; WS : ASF.Server.Web.AWS_Container; begin -- Register the servlets and filters App.Add_Servlet (Name => "compute", Server => Compute'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "compute", Pattern => "*.html"); WS.Register_Application ("/volume", App'Unchecked_Access); WS.Start; delay 60.0; end Volume_Server;
----------------------------------------------------------------------- -- volume_server -- Example of server with a servlet -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Server.Web; with ASF.Servlets; with Volume_Servlet; with Util.Log.Loggers; procedure Volume_Server is Compute : aliased Volume_Servlet.Servlet; App : aliased ASF.Servlets.Servlet_Registry; WS : ASF.Server.Web.AWS_Container; Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Volume_Server"); begin -- Register the servlets and filters App.Add_Servlet (Name => "compute", Server => Compute'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "compute", Pattern => "*.html"); WS.Register_Application ("/volume", App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/volume/compute.html"); WS.Start; delay 60.0; end Volume_Server;
Add a log message to indicate the URL to connect to
Add a log message to indicate the URL to connect to
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
62ab7134359d7902e46a3d0ba203d3f70838b7e5
matp/src/mat-types.ads
matp/src/mat-types.ads
----------------------------------------------------------------------- -- mat-types -- Global types -- 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 Interfaces; package MAT.Types is type String_Ptr is access all String; subtype Uint8 is Interfaces.Unsigned_8; subtype Uint16 is Interfaces.Unsigned_16; subtype Uint32 is Interfaces.Unsigned_32; subtype Uint64 is Interfaces.Unsigned_64; subtype Target_Addr is Interfaces.Unsigned_64; subtype Target_Size is Interfaces.Unsigned_64; subtype Target_Offset is Interfaces.Unsigned_64; type Target_Tick_Ref is new Uint64; type Target_Thread_Ref is new Uint32; subtype Target_Process_Ref is Uint32; subtype Target_Time is Target_Tick_Ref; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String; -- Format the target time to a printable representation. function Tick_Image (Value : in Target_Tick_Ref) return String; function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref; end MAT.Types;
----------------------------------------------------------------------- -- mat-types -- Global types -- 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 Interfaces; package MAT.Types is pragma Preelaborate; type String_Ptr is access all String; subtype Uint8 is Interfaces.Unsigned_8; subtype Uint16 is Interfaces.Unsigned_16; subtype Uint32 is Interfaces.Unsigned_32; subtype Uint64 is Interfaces.Unsigned_64; subtype Target_Addr is Interfaces.Unsigned_64; subtype Target_Size is Interfaces.Unsigned_64; subtype Target_Offset is Interfaces.Unsigned_64; type Target_Tick_Ref is new Uint64; type Target_Thread_Ref is new Uint32; subtype Target_Process_Ref is Uint32; subtype Target_Time is Target_Tick_Ref; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint32; Length : in Positive := 8) return String; -- Return an hexadecimal string representation of the value. function Hex_Image (Value : in Uint64; Length : in Positive := 16) return String; -- Format the target time to a printable representation. function Tick_Image (Value : in Target_Tick_Ref) return String; function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref; end MAT.Types;
Add pragma Preelaborate
Add pragma Preelaborate
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
51b61d8e55732271d41066fa3a9745a208281253
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; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- 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; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); 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; 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; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); 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;
Implement the new function Get_Policy_Index
Implement the new function Get_Policy_Index
Ada
apache-2.0
stcarrez/ada-security
12b7b51f5d9240bed140e86c0aced75395bb10fc
awa/src/awa-users-beans.adb
awa/src/awa-users-beans.adb
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with ASF.Events.Actions; with ASF.Contexts.Faces; with AWA.Users.Principals; package body AWA.Users.Beans is use AWA.Users.Models; -- ------------------------------ -- Action to register a user -- ------------------------------ procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); end Register_User; -- ------------------------------ -- Action to verify the user after the registration -- ------------------------------ procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), User => User, IpAddr => "", Session => Session); Outcome := To_Unbounded_String ("success"); end Verify_User; -- ------------------------------ -- Action to trigger the lost password email process. -- ------------------------------ procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); end Lost_Password; -- ------------------------------ -- Action to validate the reset password key and set a new password. -- ------------------------------ procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; User : in AWA.Users.Models.User_Ref; Sess : in AWA.Users.Models.Session_Ref) is Principal : constant Principals.Principal_Access := Principals.Create (User, Sess); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); Name : constant String := "User: " & User.Get_Name; begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (User, Session); end Authenticate_User; -- ------------------------------ -- Create an authenticate bean. -- ------------------------------ function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Module.Get_User_Manager; return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "password" then return Util.Beans.Objects.To_Object (From.Password); elsif Name = "key" then return Util.Beans.Objects.To_Object (From.Access_Key); 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 Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "password" then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "key" then From.Access_Key := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; end AWA.Users.Beans;
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with ASF.Events.Actions; with ASF.Contexts.Faces; with AWA.Users.Principals; package body AWA.Users.Beans is use AWA.Users.Models; -- ------------------------------ -- Action to register a user -- ------------------------------ procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Email : Email_Ref; begin Email.Set_Email (Data.Email); User.Set_First_Name (Data.First_Name); User.Set_Last_Name (Data.Last_Name); User.Set_Password (Data.Password); Data.Manager.Create_User (User => User, Email => Email); Outcome := To_Unbounded_String ("success"); end Register_User; -- ------------------------------ -- Action to verify the user after the registration -- ------------------------------ procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Verify_User (Key => To_String (Data.Access_Key), User => User, IpAddr => "", Session => Session); Data.Set_Session_Principal (User, Session); Outcome := To_Unbounded_String ("success"); end Verify_User; -- ------------------------------ -- Action to trigger the lost password email process. -- ------------------------------ procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is begin Data.Manager.Lost_Password (Email => To_String (Data.Email)); Outcome := To_Unbounded_String ("success"); end Lost_Password; -- ------------------------------ -- Action to validate the reset password key and set a new password. -- ------------------------------ procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Reset_Password (Key => To_String (Data.Access_Key), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); end Reset_Password; procedure Set_Session_Principal (Data : in Authenticate_Bean; User : in AWA.Users.Models.User_Ref; Sess : in AWA.Users.Models.Session_Ref) is Principal : constant Principals.Principal_Access := Principals.Create (User, Sess); Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; Session : ASF.Sessions.Session := Ctx.Get_Session (Create => True); Name : constant String := "User: " & User.Get_Name; begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Action to authenticate a user (password authentication). -- ------------------------------ procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String) is User : User_Ref; Session : Session_Ref; begin Data.Manager.Authenticate (Email => To_String (Data.Email), Password => To_String (Data.Password), IpAddr => "", User => User, Session => Session); Outcome := To_Unbounded_String ("success"); Data.Set_Session_Principal (User, Session); end Authenticate_User; -- ------------------------------ -- Create an authenticate bean. -- ------------------------------ function Create_Authenticate_Bean (Module : in AWA.Users.Module.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : Authenticate_Bean_Access := new Authenticate_Bean; begin Object.Module := Module; Object.Manager := AWA.Users.Module.Get_User_Manager; return Object.all'Access; end Create_Authenticate_Bean; -- The code below this line could be generated automatically by an Asis tool. package Authenticate_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Authenticate_User, Name => "authenticate"); package Register_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Register_User, Name => "register"); package Verify_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Verify_User, Name => "verify"); package Lost_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Lost_Password, Name => "lostPassword"); package Reset_Password_Binding is new ASF.Events.Actions.Action_Method.Bind (Bean => Authenticate_Bean, Method => Reset_Password, Name => "resetPassword"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Authenticate_Binding.Proxy'Access, Register_Binding.Proxy'Access, Verify_Binding.Proxy'Access, Lost_Password_Binding.Proxy'Access, Reset_Password_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "password" then return Util.Beans.Objects.To_Object (From.Password); elsif Name = "key" then return Util.Beans.Objects.To_Object (From.Access_Key); 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 Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "password" then From.Password := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "key" then From.Access_Key := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is begin return Binding_Array'Access; end Get_Method_Bindings; end AWA.Users.Beans;
Set the user principal after the verification key is valid
Set the user principal after the verification key is valid
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
bda3e197168456b795ab7691d8440dde13444384
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; end record; end Gen.Artifacts.Docs;
Declare the Write_Line procedure on the Document_Formatter
Declare the Write_Line procedure on the Document_Formatter
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
c7a652f0bbff0714135204bee97381897b715ddf
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; end record; end Gen.Artifacts.Docs;
Declare the Start_Document procedure
Declare the Start_Document procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
90dedb2fd764e2ec03a95d0ff1bb37067b744beb
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; 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); overriding procedure Finalize (Stream : in out Encoder_Stream); end Util.Streams.Buffered.Encoders;
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 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.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.Input_Output_Buffer_Stream with record Transform : Encoder; Flushed : Boolean := False; end record; -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Encoder_Stream; Size : in Positive); -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. procedure Produces (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Initialize the stream to read the given streams. procedure Consumes (Stream : in out Encoder_Stream; Input : access Input_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); -- 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 Encoder_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- 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); overriding procedure Finalize (Stream : in out Encoder_Stream); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Encoder_Stream); end Util.Streams.Buffered.Encoders;
Refactor the Util.Stream.Buffered stream - allow to use the target stream with Read (pull model) and Write (push model)
Refactor the Util.Stream.Buffered stream - allow to use the target stream with Read (pull model) and Write (push model)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1c4e2892e7c62363f5f819e90df5ff861b604a15
awa/plugins/awa-sysadmin/src/awa-sysadmin-modules.adb
awa/plugins/awa-sysadmin/src/awa-sysadmin-modules.adb
----------------------------------------------------------------------- -- awa-sysadmin-modules -- Module sysadmin -- Copyright (C) 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 AWA.Applications; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Sysadmin.Models; with Util.Log.Loggers; with ADO.Sessions; with ADO.Statements; with ADO.Queries; with ADO.Utils.Serialize; with Servlet.Rest; with Swagger.Servers.Operation; with AWA.Sysadmin.Beans; package body AWA.Sysadmin.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Sysadmin.Module"); package Register is new AWA.Modules.Beans (Module => Sysadmin_Module, Module_Access => Sysadmin_Module_Access); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); procedure List_Sessions (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); procedure List_Jobs (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); package API_List_Users is new Swagger.Servers.Operation (Handler => List_Users, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/users"); package API_List_Sessions is new Swagger.Servers.Operation (Handler => List_Sessions, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/sessions"); package API_List_Jobs is new Swagger.Servers.Operation (Handler => List_Jobs, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/jobs"); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List users"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_User_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Users; procedure List_Sessions (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List sessions"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_Session_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Sessions; procedure List_Jobs (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List jobs"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_Job_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Jobs; -- ------------------------------ -- Initialize the sysadmin module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Sysadmin_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the sysadmin module"); App.Add_Servlet ("sysadmin", Plugin.API_Servlet'Unchecked_Access); App.Add_Filter ("sysadmin-filter", Plugin.API_Filter'Unchecked_Access); Register.Register (Plugin => Plugin, Name => "AWA.Sysadmin.Beans.Authenticate_Bean", Handler => AWA.Sysadmin.Beans.Create_Authenticate_Bean'Access); App.Add_Mapping (Name => "sysadmin", Pattern => "/sysadmin/api/*"); AWA.Modules.Module (Plugin).Initialize (App, Props); Servlet.Rest.Register (App.all, API_List_Users.Definition); Servlet.Rest.Register (App.all, API_List_Sessions.Definition); Servlet.Rest.Register (App.all, API_List_Jobs.Definition); end Initialize; -- ------------------------------ -- Get the sysadmin module. -- ------------------------------ function Get_Sysadmin_Module return Sysadmin_Module_Access is function Get is new AWA.Modules.Get (Sysadmin_Module, Sysadmin_Module_Access, NAME); begin return Get; end Get_Sysadmin_Module; end AWA.Sysadmin.Modules;
----------------------------------------------------------------------- -- awa-sysadmin-modules -- Module sysadmin -- Copyright (C) 2019, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Sysadmin.Models; with Util.Log.Loggers; with ADO.Sessions; with ADO.Statements; with ADO.Queries; with ADO.Utils.Serialize; with Servlet.Rest; with Swagger.Servers.Operation; with AWA.Sysadmin.Beans; package body AWA.Sysadmin.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Sysadmin.Module"); package Register is new AWA.Modules.Beans (Module => Sysadmin_Module, Module_Access => Sysadmin_Module_Access); Mimes : aliased constant Swagger.Servers.Mime_List := (1 => Swagger.Servers.Mime_Json, 2 => Swagger.Servers.Mime_Xml); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); procedure List_Sessions (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); procedure List_Jobs (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type); package API_List_Users is new Swagger.Servers.Operation (Handler => List_Users, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/users", Mimes => Mimes'Access); package API_List_Sessions is new Swagger.Servers.Operation (Handler => List_Sessions, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/sessions", Mimes => Mimes'Access); package API_List_Jobs is new Swagger.Servers.Operation (Handler => List_Jobs, Method => Swagger.Servers.GET, URI => "/sysadmin/api/v1/jobs", Mimes => Mimes'Access); procedure List_Users (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List users"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_User_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Users; procedure List_Sessions (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List sessions"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_Session_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Sessions; procedure List_Jobs (Req : in out Swagger.Servers.Request'Class; Reply : in out Swagger.Servers.Response'Class; Stream : in out Swagger.Servers.Output_Stream'Class; Context : in out Swagger.Servers.Context_Type) is pragma Unreferenced (Req, Reply); Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module; Session : constant ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Stmt : ADO.Statements.Query_Statement; begin Log.Info ("List jobs"); Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_Job_List); Stmt := Session.Create_Statement (Query); Stmt.Execute; Stream.Start_Document; ADO.Utils.Serialize.Write_Query (Stream, "", Stmt); Stream.End_Document; Context.Set_Status (200); end List_Jobs; -- ------------------------------ -- Initialize the sysadmin module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Sysadmin_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the sysadmin module"); App.Add_Servlet ("sysadmin", Plugin.API_Servlet'Unchecked_Access); App.Add_Filter ("sysadmin-filter", Plugin.API_Filter'Unchecked_Access); Register.Register (Plugin => Plugin, Name => "AWA.Sysadmin.Beans.Authenticate_Bean", Handler => AWA.Sysadmin.Beans.Create_Authenticate_Bean'Access); App.Add_Mapping (Name => "sysadmin", Pattern => "/sysadmin/api/*"); AWA.Modules.Module (Plugin).Initialize (App, Props); Servlet.Rest.Register (App.all, API_List_Users.Definition); Servlet.Rest.Register (App.all, API_List_Sessions.Definition); Servlet.Rest.Register (App.all, API_List_Jobs.Definition); end Initialize; -- ------------------------------ -- Get the sysadmin module. -- ------------------------------ function Get_Sysadmin_Module return Sysadmin_Module_Access is function Get is new AWA.Modules.Get (Sysadmin_Module, Sysadmin_Module_Access, NAME); begin return Get; end Get_Sysadmin_Module; end AWA.Sysadmin.Modules;
Update to define the supported response mime types
Update to define the supported response mime types
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f34bca1bb0beed7af7bb3db909d4efa4d515efea
src/ado-databases.ads
src/ado-databases.ads
----------------------------------------------------------------------- -- ADO Databases -- Database Connections -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with ADO.Drivers.Connections; package ADO.Databases 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); -- --------- -- Database connection -- --------- -- Read-only database connection (or slave connection). -- type Connection is tagged private; -- Get the database connection status. function Get_Status (Database : in Connection) return Connection_Status; -- Close the database connection procedure Close (Database : in out Connection); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Connection; Query : in String) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Connection; Schema : out ADO.Schemas.Schema_Definition); -- Get the database driver which manages this connection. function Get_Driver (Database : in Connection) return ADO.Drivers.Connections.Driver_Access; -- Get the database driver index. function Get_Driver_Index (Database : in Connection) return ADO.Drivers.Driver_Index; -- Get a database connection identifier. function Get_Ident (Database : in Connection) return String; -- --------- -- Master Database connection -- --------- -- Read-write database connection. type Master_Connection is new Connection with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Connection); -- Commit the current transaction. procedure Commit (Database : in out Master_Connection); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Connection); -- Execute an SQL statement -- procedure Execute (Database : in Master_Connection; -- SQL : in Query_String); -- Execute an SQL statement -- procedure Execute (Database : in Master_Connection; -- SQL : in Query_String; -- Id : out Identifier); -- Create a delete statement. function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an insert statement. function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; -- Create an update statement. function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- ------------------------------ -- The database connection source -- ------------------------------ -- The <b>DataSource</b> is the factory for getting a connection to the database. -- It contains the configuration properties to define which database driver must -- be used and which connection parameters the driver has to use to establish -- the connection. type DataSource is new ADO.Drivers.Connections.Configuration with private; type DataSource_Access is access all DataSource'Class; -- Attempts to establish a connection with the data source -- that this DataSource object represents. function Get_Connection (Controller : in DataSource) return Master_Connection'Class; -- ------------------------------ -- Replicated Data Source -- ------------------------------ -- The replicated data source supports a Master/Slave database configuration. -- When using this data source, the master is used to execute -- update, insert, delete and also query statements. The slave is used -- to execute query statements. The master and slave are represented by -- two separate data sources. This allows to have a master on one server, -- use a specific user/password and get a slave on another server with other -- credentials. type Replicated_DataSource is new DataSource with private; type Replicated_DataSource_Access is access all Replicated_DataSource'Class; -- Set the master data source procedure Set_Master (Controller : in out Replicated_DataSource; Master : in DataSource_Access); -- Get the master data source function Get_Master (Controller : in Replicated_DataSource) return DataSource_Access; -- Set the slave data source procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in DataSource_Access); -- Get the slace data source function Get_Slave (Controller : in Replicated_DataSource) return DataSource_Access; -- Get a slave database connection function Get_Slave_Connection (Controller : in Replicated_DataSource) return Connection'Class; private type Connection is new Ada.Finalization.Controlled with record Impl : ADO.Drivers.Connections.Database_Connection_Access := null; end record; -- Adjust the connection reference counter overriding procedure Adjust (Object : in out Connection); -- Releases the connection reference counter overriding procedure Finalize (Object : in out Connection); type Master_Connection is new Connection with null record; type DataSource is new ADO.Drivers.Connections.Configuration with null record; type Replicated_DataSource is new DataSource with record Master : DataSource_Access := null; Slave : DataSource_Access := null; end record; end ADO.Databases;
----------------------------------------------------------------------- -- 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 ADO.Statements; with ADO.Schemas; with ADO.Drivers.Connections; package ADO.Databases 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); -- --------- -- Database connection -- --------- -- Read-only database connection (or slave connection). -- type Connection is tagged private; -- Get the database connection status. function Get_Status (Database : in Connection) return Connection_Status; -- Close the database connection procedure Close (Database : in out Connection); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Connection; Query : in String) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Connection; Schema : out ADO.Schemas.Schema_Definition); -- Get the database driver which manages this connection. function Get_Driver (Database : in Connection) return ADO.Drivers.Connections.Driver_Access; -- Get the database driver index. function Get_Driver_Index (Database : in Connection) return ADO.Drivers.Driver_Index; -- Get a database connection identifier. function Get_Ident (Database : in Connection) return String; -- --------- -- Master Database connection -- --------- -- Read-write database connection. type Master_Connection is new Connection with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Connection); -- Commit the current transaction. procedure Commit (Database : in out Master_Connection); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Connection); -- Execute an SQL statement -- procedure Execute (Database : in Master_Connection; -- SQL : in Query_String); -- Execute an SQL statement -- procedure Execute (Database : in Master_Connection; -- SQL : in Query_String; -- Id : out Identifier); -- Create a delete statement. function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an insert statement. function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; -- Create an update statement. function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- ------------------------------ -- The database connection source -- ------------------------------ -- The <b>DataSource</b> is the factory for getting a connection to the database. -- It contains the configuration properties to define which database driver must -- be used and which connection parameters the driver has to use to establish -- the connection. type DataSource is new ADO.Drivers.Connections.Configuration with private; type DataSource_Access is access all DataSource'Class; -- Attempts to establish a connection with the data source -- that this DataSource object represents. function Get_Connection (Controller : in DataSource) return Master_Connection'Class; -- ------------------------------ -- Replicated Data Source -- ------------------------------ -- The replicated data source supports a Master/Slave database configuration. -- When using this data source, the master is used to execute -- update, insert, delete and also query statements. The slave is used -- to execute query statements. The master and slave are represented by -- two separate data sources. This allows to have a master on one server, -- use a specific user/password and get a slave on another server with other -- credentials. type Replicated_DataSource is new DataSource with private; type Replicated_DataSource_Access is access all Replicated_DataSource'Class; -- Set the master data source procedure Set_Master (Controller : in out Replicated_DataSource; Master : in DataSource_Access); -- Get the master data source function Get_Master (Controller : in Replicated_DataSource) return DataSource_Access; -- Set the slave data source procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in DataSource_Access); -- Get the slace data source function Get_Slave (Controller : in Replicated_DataSource) return DataSource_Access; -- Get a slave database connection function Get_Slave_Connection (Controller : in Replicated_DataSource) return Connection'Class; private type Connection is new ADO.Drivers.Connections.Ref.Ref with null record; type Master_Connection is new Connection with null record; type DataSource is new ADO.Drivers.Connections.Configuration with null record; type Replicated_DataSource is new DataSource with record Master : DataSource_Access := null; Slave : DataSource_Access := null; end record; end ADO.Databases;
Change the implementation to use the Util.Refs package
Change the implementation to use the Util.Refs package
Ada
apache-2.0
stcarrez/ada-ado
5f9a05a867e32b4f0bb754ee8f52df7289b527ee
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 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.Containers; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with ADO.Sessions.Entities; with AWA.Helpers.Requests; with AWA.Workspaces.Models; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is use type ADO.Identifier; Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); if Part.Get_Size > 100_000 then Manager.Save (Bean, Part, AWA.Storages.Models.FILE); else Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end if; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Bean); begin Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Workspaces.Models.WORKSPACE_TABLE, Session); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 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.Containers; with Util.Log.Loggers; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is use type ADO.Identifier; Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); if Part.Get_Size > 100_000 then Manager.Save (Bean, Part, AWA.Storages.Models.FILE); else Manager.Save (Bean, Part, AWA.Storages.Models.DATABASE); end if; exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin Load_Folders (Storage); if Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then Manager.Load_Folder (From.Folder, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); From.Flags (INIT_FOLDER) := True; end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then if not List.Init_Flags (INIT_FILE_LIST) then Load_Files (List); end if; return Util.Beans.Objects.To_Object (Value => List.Files_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then if not List.Init_Flags (INIT_FOLDER_LIST) then Load_Folders (List); end if; return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then if not List.Init_Flags (INIT_FOLDER) then Load_Folder (List); end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; end AWA.Storages.Beans;
Add error support when uploading a file Use the $entity_type cache
Add error support when uploading a file Use the $entity_type cache
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0aa412e668e40758cfc5ff6d123847fa9f800971
awa/plugins/awa-mail/src/awa-mail-components-messages.adb
awa/plugins/awa-mail/src/awa-mail-components-messages.adb
----------------------------------------------------------------------- -- awa-mail-components-messages -- Mail UI Message -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with AWA.Mail.Clients; package body AWA.Mail.Components.Messages is -- ------------------------------ -- Set the mail message instance. -- ------------------------------ procedure Set_Message (UI : in out UIMailMessage; Message : in AWA.Mail.Clients.Mail_Message_Access) is begin UI.Message := Message; end Set_Message; -- ------------------------------ -- Get the mail message instance. -- ------------------------------ overriding function Get_Message (UI : in UIMailMessage) return AWA.Mail.Clients.Mail_Message_Access is begin return UI.Message; end Get_Message; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIMailMessage; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type AWA.Mail.Clients.Mail_Message_Access; begin if UI.Message /= null and UI.Is_Rendered (Context) then UI.Message.Send; end if; end Encode_End; -- ------------------------------ -- Finalize and release the mail message. -- ------------------------------ overriding procedure Finalize (UI : in out UIMailMessage) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Mail.Clients.Mail_Message'Class, Name => AWA.Mail.Clients.Mail_Message_Access); begin Free (UI.Message); end Finalize; -- ------------------------------ -- Render the mail subject and initializes the message with its content. -- ------------------------------ overriding procedure Encode_Children (UI : in UIMailSubject; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Msg : constant AWA.Mail.Clients.Mail_Message_Access := UI.Get_Message; begin Msg.Set_Subject (Content); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; -- ------------------------------ -- Render the mail body and initializes the message with its content. -- ------------------------------ overriding procedure Encode_Children (UI : in UIMailBody; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Msg : constant AWA.Mail.Clients.Mail_Message_Access := UI.Get_Message; begin Msg.Set_Body (Content); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; end AWA.Mail.Components.Messages;
----------------------------------------------------------------------- -- awa-mail-components-messages -- Mail UI Message -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Unbounded; with Util.Beans.Objects; with ASF.Components.Base; with AWA.Mail.Clients; package body AWA.Mail.Components.Messages is use Ada.Strings.Unbounded; use type ASF.Components.Base.UIComponent_Access; -- ------------------------------ -- Set the mail message instance. -- ------------------------------ procedure Set_Message (UI : in out UIMailMessage; Message : in AWA.Mail.Clients.Mail_Message_Access) is begin UI.Message := Message; end Set_Message; -- ------------------------------ -- Get the mail message instance. -- ------------------------------ overriding function Get_Message (UI : in UIMailMessage) return AWA.Mail.Clients.Mail_Message_Access is begin return UI.Message; end Get_Message; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIMailMessage; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type AWA.Mail.Clients.Mail_Message_Access; begin if UI.Message /= null and UI.Is_Rendered (Context) then UI.Message.Send; end if; end Encode_End; -- ------------------------------ -- Finalize and release the mail message. -- ------------------------------ overriding procedure Finalize (UI : in out UIMailMessage) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Mail.Clients.Mail_Message'Class, Name => AWA.Mail.Clients.Mail_Message_Access); begin Free (UI.Message); end Finalize; -- ------------------------------ -- Render the mail subject and initializes the message with its content. -- ------------------------------ overriding procedure Encode_Children (UI : in UIMailSubject; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in String); procedure Process (Content : in String) is Msg : constant AWA.Mail.Clients.Mail_Message_Access := UI.Get_Message; begin Msg.Set_Subject (Content); end Process; begin UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; -- ------------------------------ -- Render the mail body and initializes the message with its content. -- ------------------------------ overriding procedure Encode_Children (UI : in UIMailBody; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Process (Content : in Unbounded_String); procedure Process_Alternative (Content : in Unbounded_String); Body_Type : Util.Beans.Objects.Object; Alternative_Content : Unbounded_String; procedure Process_Alternative (Content : in Unbounded_String) is begin Alternative_Content := Content; end Process_Alternative; procedure Process (Content : in Unbounded_String) is Msg : constant AWA.Mail.Clients.Mail_Message_Access := UI.Get_Message; Typ : constant String := Util.Beans.Objects.To_String (Body_Type); begin if not Util.Beans.Objects.Is_Empty (Body_Type) then Msg.Set_Body (Content, Alternative_Content, Typ); else Msg.Set_Body (Content, Alternative_Content); end if; end Process; Alternative_Facet : ASF.Components.Base.UIComponent_Access; begin Body_Type := UI.Get_Attribute (Name => "type", Context => Context); Alternative_Facet := UI.Get_Facet (ALTERNATIVE_NAME); if Alternative_Facet /= null then Alternative_Facet.Wrap_Encode_Children (Context, Process_Alternative'Access); end if; UI.Wrap_Encode_Children (Context, Process'Access); end Encode_Children; end AWA.Mail.Components.Messages;
Update mail body Encode_Children to look at the optional 'alternative' facet, render it and include it in the mail body as multipart alternative
Update mail body Encode_Children to look at the optional 'alternative' facet, render it and include it in the mail body as multipart alternative
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d9132c8ac77e862c6759bd22992ee6cbf3a67c12
orka/src/orka/implementation/orka-rendering-programs-modules.adb
orka/src/orka/implementation/orka-rendering-programs-modules.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with GL.Debug; with Orka.Strings; package body Orka.Rendering.Programs.Modules is use GL.Debug; package Messages is new GL.Debug.Messages (Third_Party, Other); function Trim_Image (Value : Integer) return String is (Orka.Strings.Trim (Integer'Image (Value))); procedure Load_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Location : Resources.Locations.Location_Ptr; Path : String) is begin if Path /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); Source : constant Resources.Byte_Array_Pointers.Pointer := Location.Read_Data (Path); Text : String renames Resources.Convert (Source.Get); begin Shader.Set_Source (Text); Shader.Compile; if not Shader.Compile_Status then raise Shader_Compile_Error with Path & ":" & Shader.Info_Log; end if; Messages.Log (Notification, "Compiled shader " & Path); Messages.Log (Notification, " size: " & Trim_Image (Orka.Strings.Lines (Text)) & " lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)"); Messages.Log (Notification, " kind: " & Shader_Kind'Image); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Load_And_Compile; procedure Set_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Source : String) is begin if Source /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); begin Shader.Set_Source (Source); Shader.Compile; if not Shader.Compile_Status then raise Shader_Compile_Error with Shader_Kind'Image & ":" & Shader.Info_Log; end if; Messages.Log (Notification, "Compiled string with " & Trim_Image (Source'Length) & " characters"); Messages.Log (Notification, " size: " & Trim_Image (Orka.Strings.Lines (Source)) & " lines"); Messages.Log (Notification, " kind: " & Shader_Kind'Image); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Set_And_Compile; function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Set_And_Compile (Result, Vertex_Shader, VS); Set_And_Compile (Result, Tess_Control_Shader, TCS); Set_And_Compile (Result, Tess_Evaluation_Shader, TES); Set_And_Compile (Result, Geometry_Shader, GS); Set_And_Compile (Result, Fragment_Shader, FS); Set_And_Compile (Result, Compute_Shader, CS); end return; end Create_Module_From_Sources; function Create_Module (Location : Resources.Locations.Location_Ptr; VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Load_And_Compile (Result, Vertex_Shader, Location, VS); Load_And_Compile (Result, Tess_Control_Shader, Location, TCS); Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES); Load_And_Compile (Result, Geometry_Shader, Location, GS); Load_And_Compile (Result, Fragment_Shader, Location, FS); Load_And_Compile (Result, Compute_Shader, Location, CS); end return; end Create_Module; procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is use GL.Objects.Shaders; procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is Holder : Shader_Holder.Holder renames Subject.Shaders (Stage); begin if not Holder.Is_Empty then Program.GL_Program.Attach (Holder.Element); Program.Stages (Stage) := True; end if; end Attach; begin for Module of Modules loop Attach (Module, Vertex_Shader); Attach (Module, Tess_Control_Shader); Attach (Module, Tess_Evaluation_Shader); Attach (Module, Geometry_Shader); Attach (Module, Fragment_Shader); Attach (Module, Compute_Shader); end loop; end Attach_Shaders; procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is use GL.Objects.Shaders; procedure Detach (Holder : Shader_Holder.Holder) is begin if not Holder.Is_Empty then Program.GL_Program.Detach (Holder.Element); end if; end Detach; begin for Module of Modules loop Detach (Module.Shaders (Vertex_Shader)); Detach (Module.Shaders (Tess_Control_Shader)); Detach (Module.Shaders (Tess_Evaluation_Shader)); Detach (Module.Shaders (Geometry_Shader)); Detach (Module.Shaders (Fragment_Shader)); Detach (Module.Shaders (Compute_Shader)); end loop; end Detach_Shaders; end Orka.Rendering.Programs.Modules;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with GL.Debug; with Orka.Strings; with Orka.Terminals; package body Orka.Rendering.Programs.Modules is use GL.Debug; package Messages is new GL.Debug.Messages (Third_Party, Other); function Trim_Image (Value : Integer) return String is (Orka.Strings.Trim (Integer'Image (Value))); procedure Log_Error_With_Source (Text, Info_Log, Message : String) is package SF renames Ada.Strings.Fixed; package L1 renames Ada.Characters.Latin_1; Extra_Rows : constant := 2; Line_Number_Padding : constant := 2; Separator : constant String := " | "; use Orka.Strings; use SF; use all type Orka.Terminals.Color; use all type Orka.Terminals.Style; begin declare Log_Parts : constant Orka.Strings.String_List := Split (Info_Log, ":", 3); Message_Parts : constant String_List := Split (Trim (+Log_Parts (3)), ": ", 2); Message_Kind_Color : constant Orka.Terminals.Color := (if +Message_Parts (1) = "error" then Red elsif +Message_Parts (2) = "warning" then Yellow elsif +Message_Parts (2) = "note" then Cyan else Default); Message_Kind : constant String := Orka.Terminals.Colorize (+Message_Parts (1) & ":", Foreground => Message_Kind_Color); Message_Value : constant String := Orka.Terminals.Colorize (+Message_Parts (2), Attribute => Bold); ------------------------------------------------------------------------- Lines : constant Orka.Strings.String_List := Orka.Strings.Split (Text, "" & L1.LF); Error_Row : constant Positive := Positive'Value (+Orka.Strings.Split (+Log_Parts (2), "(", 2) (1)); First_Row : constant Positive := Positive'Max (Lines'First, Error_Row - Extra_Rows); Last_Row : constant Positive := Positive'Min (Lines'Last, Error_Row + Extra_Rows); Line_Digits : constant Positive := Trim (Last_Row'Image)'Length + Line_Number_Padding; begin Messages.Log (High, Message); for Row_Index in First_Row .. Last_Row loop declare Row_Image : constant String := SF.Tail (Trim (Row_Index'Image), Line_Digits); Row_Image_Colorized : constant String := Orka.Terminals.Colorize (Row_Image, Attribute => Dark); Line_Image : constant String := +Lines (Row_Index); First_Index_Line : constant Natural := SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Forward); Last_Index_Line : constant Natural := SF.Index_Non_Blank (Line_Image, Going => Ada.Strings.Backward); Error_Indicator : constant String := Orka.Terminals.Colorize (Natural'Max (0, First_Index_Line - 1) * " " & (Last_Index_Line - First_Index_Line + 1) * "^", Foreground => Green, Attribute => Bold); Prefix_Image : constant String := (Row_Image'Length + Separator'Length) * " "; begin Messages.Log (High, Row_Image_Colorized & Separator & Line_Image); if Row_Index = Error_Row then Messages.Log (High, Prefix_Image & Error_Indicator); Messages.Log (High, Prefix_Image & ">>> " & Message_Kind & " " & Message_Value); end if; end; end loop; end; exception when others => -- Continue if parsing Info_Log fails null; end Log_Error_With_Source; procedure Load_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Location : Resources.Locations.Location_Ptr; Path : String) is begin if Path /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); Source : constant Resources.Byte_Array_Pointers.Pointer := Location.Read_Data (Path); Text : String renames Resources.Convert (Source.Get); begin Shader.Set_Source (Text); Shader.Compile; if not Shader.Compile_Status then declare Log : constant String := Shader.Info_Log; begin Log_Error_With_Source (Text, Log, "Compiling shader " & Path & " failed:"); raise Shader_Compile_Error with Path & ":" & Log; end; end if; Messages.Log (Notification, "Compiled shader " & Path); Messages.Log (Notification, " size: " & Trim_Image (Orka.Strings.Lines (Text)) & " lines (" & Trim_Image (Source.Get.Value'Length) & " bytes)"); Messages.Log (Notification, " kind: " & Shader_Kind'Image); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Load_And_Compile; procedure Set_And_Compile (Object : in out Module; Shader_Kind : GL.Objects.Shaders.Shader_Type; Source : String) is begin if Source /= "" then pragma Assert (Object.Shaders (Shader_Kind).Is_Empty); declare Shader : GL.Objects.Shaders.Shader (Kind => Shader_Kind); begin Shader.Set_Source (Source); Shader.Compile; if not Shader.Compile_Status then declare Log : constant String := Shader.Info_Log; begin Log_Error_With_Source (Source, Log, "Compiling " & Shader_Kind'Image & " shader failed:"); raise Shader_Compile_Error with Shader_Kind'Image & ":" & Log; end; end if; Messages.Log (Notification, "Compiled string with " & Trim_Image (Source'Length) & " characters"); Messages.Log (Notification, " size: " & Trim_Image (Orka.Strings.Lines (Source)) & " lines"); Messages.Log (Notification, " kind: " & Shader_Kind'Image); Object.Shaders (Shader_Kind).Replace_Element (Shader); end; end if; end Set_And_Compile; function Create_Module_From_Sources (VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Set_And_Compile (Result, Vertex_Shader, VS); Set_And_Compile (Result, Tess_Control_Shader, TCS); Set_And_Compile (Result, Tess_Evaluation_Shader, TES); Set_And_Compile (Result, Geometry_Shader, GS); Set_And_Compile (Result, Fragment_Shader, FS); Set_And_Compile (Result, Compute_Shader, CS); end return; end Create_Module_From_Sources; function Create_Module (Location : Resources.Locations.Location_Ptr; VS, TCS, TES, GS, FS, CS : String := "") return Module is use GL.Objects.Shaders; begin return Result : Module do Load_And_Compile (Result, Vertex_Shader, Location, VS); Load_And_Compile (Result, Tess_Control_Shader, Location, TCS); Load_And_Compile (Result, Tess_Evaluation_Shader, Location, TES); Load_And_Compile (Result, Geometry_Shader, Location, GS); Load_And_Compile (Result, Fragment_Shader, Location, FS); Load_And_Compile (Result, Compute_Shader, Location, CS); end return; end Create_Module; procedure Attach_Shaders (Modules : Module_Array; Program : in out Programs.Program) is use GL.Objects.Shaders; procedure Attach (Subject : Module; Stage : GL.Objects.Shaders.Shader_Type) is Holder : Shader_Holder.Holder renames Subject.Shaders (Stage); begin if not Holder.Is_Empty then Program.GL_Program.Attach (Holder.Element); Program.Stages (Stage) := True; end if; end Attach; begin for Module of Modules loop Attach (Module, Vertex_Shader); Attach (Module, Tess_Control_Shader); Attach (Module, Tess_Evaluation_Shader); Attach (Module, Geometry_Shader); Attach (Module, Fragment_Shader); Attach (Module, Compute_Shader); end loop; end Attach_Shaders; procedure Detach_Shaders (Modules : Module_Array; Program : Programs.Program) is use GL.Objects.Shaders; procedure Detach (Holder : Shader_Holder.Holder) is begin if not Holder.Is_Empty then Program.GL_Program.Detach (Holder.Element); end if; end Detach; begin for Module of Modules loop Detach (Module.Shaders (Vertex_Shader)); Detach (Module.Shaders (Tess_Control_Shader)); Detach (Module.Shaders (Tess_Evaluation_Shader)); Detach (Module.Shaders (Geometry_Shader)); Detach (Module.Shaders (Fragment_Shader)); Detach (Module.Shaders (Compute_Shader)); end loop; end Detach_Shaders; end Orka.Rendering.Programs.Modules;
Print a few lines of source text when compiling shader fails
orka: Print a few lines of source text when compiling shader fails Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
c302e218ca80fcbe0f419bb6b90754ece86de709
regtests/gen-artifacts-xmi-tests.adb
regtests/gen-artifacts-xmi-tests.adb
----------------------------------------------------------------------- -- gen-xmi-tests -- Tests for xmi -- 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.Test_Caller; with Gen.Generator; package body Gen.Artifacts.XMI.Tests is use Ada.Strings.Unbounded; package Caller is new Util.Test_Caller (Test, "Gen.XMI"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration", Test_Read_XMI'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Element'Access); end Add_Tests; -- ------------------------------ -- Test reading the XMI files defines in the Dynamo UML configuration repository. -- ------------------------------ procedure Test_Read_XMI (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use type Gen.Model.XMI.Model_Element_Access; procedure Check (Namespace : in String; Name : in String; Id : in String) is Empty : Gen.Model.XMI.Model_Map.Map; XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id); N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes, Empty, XMI_Id); begin T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id)); Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name"); end Check; begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_UML_Configuration (G); -- ArgoUML Integer DataType Check ("default-uml14.xmi", "Integer", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C"); -- ArgoUML String DataType Check ("default-uml14.xmi", "String", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E"); -- ArgoUML documentation TagDefinition Check ("default-uml14.xmi", "documentation", ".:000000000000087C"); -- ArgoUML type Stereotype Check ("default-uml14.xmi", "type", ".:0000000000000842"); -- Persistence Table Stereotype Check ("Dynamo.xmi", "Table", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F"); Check ("Dynamo.xmi", "PK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50"); Check ("Dynamo.xmi", "FK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70"); Check ("Dynamo.xmi", "Bean", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72"); end Test_Read_XMI; -- ------------------------------ -- Test searching an XMI element by using a qualified name. -- ------------------------------ procedure Test_Find_Element (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use type Gen.Model.XMI.Model_Element_Access; use type Gen.Model.XMI.Stereotype_Element_Access; function Find_Stereotype is new Gen.Model.XMI.Find_Element (Element_Type => Model.XMI.Stereotype_Element, Element_Type_Access => Model.XMI.Stereotype_Element_Access); begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_UML_Configuration (G); declare S : Gen.Model.XMI.Stereotype_Element_Access; begin S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); end; end Test_Find_Element; end Gen.Artifacts.XMI.Tests;
----------------------------------------------------------------------- -- gen-xmi-tests -- Tests for xmi -- 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.Test_Caller; with Gen.Generator; package body Gen.Artifacts.XMI.Tests is use Ada.Strings.Unbounded; package Caller is new Util.Test_Caller (Test, "Gen.XMI"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Gen.XMI.Read_UML_Configuration", Test_Read_XMI'Access); Caller.Add_Test (Suite, "Test Gen.XMI.Find_Element", Test_Find_Element'Access); end Add_Tests; -- ------------------------------ -- Test reading the XMI files defines in the Dynamo UML configuration repository. -- ------------------------------ procedure Test_Read_XMI (T : in out Test) is procedure Check (Namespace : in String; Name : in String; Id : in String); A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use type Gen.Model.XMI.Model_Element_Access; procedure Check (Namespace : in String; Name : in String; Id : in String) is Empty : Gen.Model.XMI.Model_Map.Map; XMI_Id : constant Unbounded_String := To_Unbounded_String (Namespace & "#" & Id); N : constant Gen.Model.XMI.Model_Element_Access := Gen.Model.XMI.Find (A.Nodes, Empty, XMI_Id); begin T.Assert (N /= null, "Cannot find UML element " & To_String (XMI_Id)); Util.Tests.Assert_Equals (T, Name, To_String (N.Name), "Invalid element name"); end Check; begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_UML_Configuration (G); -- ArgoUML Integer DataType Check ("default-uml14.xmi", "Integer", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087C"); -- ArgoUML String DataType Check ("default-uml14.xmi", "String", "-84-17--56-5-43645a83:11466542d86:-8000:000000000000087E"); -- ArgoUML documentation TagDefinition Check ("default-uml14.xmi", "documentation", ".:000000000000087C"); -- ArgoUML type Stereotype Check ("default-uml14.xmi", "type", ".:0000000000000842"); -- Persistence Table Stereotype Check ("Dynamo.xmi", "Table", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D4F"); Check ("Dynamo.xmi", "PK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001D50"); Check ("Dynamo.xmi", "FK", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F70"); Check ("Dynamo.xmi", "Bean", "127-0-1-1--44304ba0:139c0f2a59c:-8000:0000000000001F72"); end Test_Read_XMI; -- ------------------------------ -- Test searching an XMI element by using a qualified name. -- ------------------------------ procedure Test_Find_Element (T : in out Test) is A : Artifact; G : Gen.Generator.Handler; C : constant String := Util.Tests.Get_Parameter ("config_dir", "config"); use Gen.Model.XMI; function Find_Stereotype is new Gen.Model.XMI.Find_Element (Element_Type => Stereotype_Element, Element_Type_Access => Stereotype_Element_Access); begin Gen.Generator.Initialize (G, Ada.Strings.Unbounded.To_Unbounded_String (C), False); A.Read_UML_Configuration (G); declare S : Gen.Model.XMI.Stereotype_Element_Access; begin S := Find_Stereotype (A.Nodes, "Dynamo.xmi", "ADO.Table", Gen.Model.XMI.BY_NAME); T.Assert (S /= null, "Stereotype not found"); end; end Test_Find_Element; end Gen.Artifacts.XMI.Tests;
Fix compilation warnings on unit tests
Fix compilation warnings on unit tests
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
dfba88f21cdd689582baa3240646d42acfaa0748
src/asf-models-selects.ads
src/asf-models-selects.ads
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- 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.Containers.Vectors; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Refs; package ASF.Models.Selects is -- ------------------------------ -- Select Item -- ------------------------------ -- The <b>Select_Item</b> type describes a single option of a list of options -- used by the <b>UISelectOne</b> or <b>UISelectMany</b> components. -- The select item contains: -- <ul> -- <li>A label -- <li>A value -- <li>A description -- <li>Whether the select item is disabled or not -- <li>Whether the label is escaped or not -- </ul> -- An application creates the <b>Select_Item</b> instances and passes them -- to the ASF components through an <b>Util.Beans.Objects.Object</b> value. type Select_Item is new Util.Beans.Basic.Readonly_Bean with private; type Select_Item_Access is access all Select_Item; -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object; -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Get the item label. function Get_Label (Item : in Select_Item) return Wide_Wide_String; -- Get the item value. function Get_Value (Item : in Select_Item) return Wide_Wide_String; -- Get the item description. function Get_Description (Item : in Select_Item) return Wide_Wide_String; -- Returns true if the item is disabled. function Is_Disabled (Item : in Select_Item) return Boolean; -- Returns true if the label must be escaped using HTML escape rules. function Is_Escaped (Item : in Select_Item) return Boolean; -- Returns true if the select item component is empty. function Is_Empty (Item : in Select_Item) return Boolean; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Select_Item; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Select Item List -- ------------------------------ -- The <b>Select_Item_List</b> type holds a list of <b>Select_Item</b>. -- Similar to <b>Select_Item</b>, an application builds the list items and gives it -- to the ASF components through an <b>Util.Beans.Objects.Object</b> instance. type Select_Item_List is new Util.Beans.Basic.Readonly_Bean with private; type Select_Item_List_Access is access all Select_Item_List; -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object; -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List; -- Get the number of items in the list. function Length (List : in Select_Item_List) return Natural; -- Get the select item from the list function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item; -- Add the item at the end of the list. procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class); -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) procedure Append (List : in out Select_Item_List; Label : in String; Value : in String); private use Ada.Strings.Wide_Wide_Unbounded; type Select_Item_Record is new Util.Refs.Ref_Entity with record Label : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; Description : Unbounded_Wide_Wide_String; Disabled : Boolean := False; Escape : Boolean := False; end record; type Select_Item_Record_Access is access all Select_Item_Record; package Select_Item_Refs is new Util.Refs.References (Element_Type => Select_Item_Record, Element_Access => Select_Item_Record_Access); type Select_Item is new Util.Beans.Basic.Readonly_Bean with record Item : Select_Item_Refs.Ref; end record; package Select_Item_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Select_Item); type Select_Item_Vector is new Util.Refs.Ref_Entity with record List : Select_Item_Vectors.Vector; end record; type Select_Item_Vector_Access is access all Select_Item_Vector; package Select_Item_Vector_Refs is new Util.Refs.References (Element_Type => Select_Item_Vector, Element_Access => Select_Item_Vector_Access); type Select_Item_List is new Util.Beans.Basic.Readonly_Bean with record List : Select_Item_Vector_Refs.Ref; 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 : in Select_Item_List; Name : in String) return Util.Beans.Objects.Object; end ASF.Models.Selects;
----------------------------------------------------------------------- -- asf-models-selects -- Data model for UISelectOne and UISelectMany -- 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.Containers.Vectors; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Refs; package ASF.Models.Selects is -- ------------------------------ -- Select Item -- ------------------------------ -- The <b>Select_Item</b> type describes a single option of a list of options -- used by the <b>UISelectOne</b> or <b>UISelectMany</b> components. -- The select item contains: -- <ul> -- <li>A label -- <li>A value -- <li>A description -- <li>Whether the select item is disabled or not -- <li>Whether the label is escaped or not -- </ul> -- An application creates the <b>Select_Item</b> instances and passes them -- to the ASF components through an <b>Util.Beans.Objects.Object</b> value. type Select_Item is new Util.Beans.Basic.Readonly_Bean with private; type Select_Item_Access is access all Select_Item; -- Return an Object from the select item record. -- Returns a NULL object if the item is empty. function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object; -- Return the <b>Select_Item</b> instance from a generic bean object. -- Returns an empty item if the object does not hold a <b>Select_Item</b>. function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item (Label : in String; Value : in String; Description : in String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label and value. function Create_Select_Item_Wide (Label : in Wide_Wide_String; Value : in Wide_Wide_String; Description : in Wide_Wide_String := ""; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Creates a <b>Select_Item</b> with the specified label, value and description. -- The objects are converted to a wide wide string. The empty string is used if they -- are null. function Create_Select_Item (Label : in Util.Beans.Objects.Object; Value : in Util.Beans.Objects.Object; Description : in Util.Beans.Objects.Object; Disabled : in Boolean := False; Escaped : in Boolean := True) return Select_Item; -- Get the item label. function Get_Label (Item : in Select_Item) return Wide_Wide_String; -- Get the item value. function Get_Value (Item : in Select_Item) return Wide_Wide_String; -- Get the item description. function Get_Description (Item : in Select_Item) return Wide_Wide_String; -- Returns true if the item is disabled. function Is_Disabled (Item : in Select_Item) return Boolean; -- Returns true if the label must be escaped using HTML escape rules. function Is_Escaped (Item : in Select_Item) return Boolean; -- Returns true if the select item component is empty. function Is_Empty (Item : in Select_Item) return Boolean; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Select_Item; Name : in String) return Util.Beans.Objects.Object; -- ------------------------------ -- Select Item List -- ------------------------------ -- The <b>Select_Item_List</b> type holds a list of <b>Select_Item</b>. -- Similar to <b>Select_Item</b>, an application builds the list items and gives it -- to the ASF components through an <b>Util.Beans.Objects.Object</b> instance. type Select_Item_List is new Util.Beans.Basic.List_Bean with private; type Select_Item_List_Access is access all Select_Item_List; -- Return an Object from the select item list. -- Returns a NULL object if the list is empty. function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object; -- Return the <b>Select_Item_List</b> instance from a generic bean object. -- Returns an empty list if the object does not hold a <b>Select_Item_List</b>. function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List; -- Get the number of elements in the list. overriding function Get_Count (From : in Select_Item_List) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out Select_Item_List; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in Select_Item_List) return Util.Beans.Objects.Object; -- Get the number of items in the list. function Length (List : in Select_Item_List) return Natural; -- Get the select item from the list function Get_Select_Item (List : in Select_Item_List'Class; Pos : in Positive) return Select_Item; -- Add the item at the end of the list. procedure Append (List : in out Select_Item_List; Item : in Select_Item'Class); -- Add the item at the end of the list. This is a shortcut for -- Append (Create_List_Item (Label, Value)) procedure Append (List : in out Select_Item_List; Label : in String; Value : in String); private use Ada.Strings.Wide_Wide_Unbounded; type Select_Item_Record is new Util.Refs.Ref_Entity with record Label : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; Description : Unbounded_Wide_Wide_String; Disabled : Boolean := False; Escape : Boolean := False; end record; type Select_Item_Record_Access is access all Select_Item_Record; package Select_Item_Refs is new Util.Refs.References (Element_Type => Select_Item_Record, Element_Access => Select_Item_Record_Access); type Select_Item is new Util.Beans.Basic.Readonly_Bean with record Item : Select_Item_Refs.Ref; end record; package Select_Item_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Select_Item); type Select_Item_Vector is new Util.Refs.Ref_Entity with record List : Select_Item_Vectors.Vector; end record; type Select_Item_Vector_Access is access all Select_Item_Vector; package Select_Item_Vector_Refs is new Util.Refs.References (Element_Type => Select_Item_Vector, Element_Access => Select_Item_Vector_Access); type Select_Item_List is new Util.Beans.Basic.List_Bean with record List : Select_Item_Vector_Refs.Ref; Current : aliased Select_Item; Row : Util.Beans.Objects.Object; 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 : in Select_Item_List; Name : in String) return Util.Beans.Objects.Object; end ASF.Models.Selects;
Change the Select_List_Item to implement the List_Bean interface so that a select list can be used as general purpose lists also
Change the Select_List_Item to implement the List_Bean interface so that a select list can be used as general purpose lists also
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
ec2a90725ddcfd102abcfb4018363310ff600953
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 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.Events.Targets.Event_Id_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 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 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 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.Events.Targets.Event_Id_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 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;
Implement the Create_Thread function
Implement the Create_Thread function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d3c187f84966552149005eac37d8b3556aaf3c40
awa/regtests/awa-tests.adb
awa/regtests/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Drivers; with ASF.Server.Tests; with ASF.Server.Web; with ASF.Converters.Dates; with ASF.Tests; with AWA.Users.Module; with AWA.Mail.Module; with AWA.Blogs.Module; -- with AWA.Applications; with AWA.Applications.Factory; with AWA.Services.Filters; package body AWA.Tests is App : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Users : aliased AWA.Users.Module.User_Module; Mail : aliased AWA.Mail.Module.Mail_Module; Blogs : aliased AWA.Blogs.Module.Blog_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager) is use AWA.Applications; begin ADO.Drivers.Initialize (Props); App := new AWA.Applications.Application; ASF.Tests.Initialize (Props, App.all'Access, Factory); App.Add_Filter ("service", Service_Filter'Access); App.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); declare Users : constant AWA.Users.Module.User_Module_Access := AWA.Tests.Users'Access; begin Register (App => App.all'Access, Name => AWA.Users.Module.NAME, URI => "user", Module => Users.all'Access); Register (App => App.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => App.all'Access, Name => AWA.Blogs.Module.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin App.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); WS.Register_Application ("/asfunit", App.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (App.all'Access); end; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (App.all'Access); end Set_Application_Context; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Drivers; with ASF.Server.Tests; with ASF.Server.Web; with ASF.Converters.Dates; with ASF.Tests; with AWA.Users.Module; with AWA.Mail.Module; with AWA.Blogs.Module; with AWA.Workspaces.Module; -- with AWA.Applications; with AWA.Applications.Factory; with AWA.Services.Filters; package body AWA.Tests is App : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Users : aliased AWA.Users.Module.User_Module; Workspaces : aliased AWA.Workspaces.Module.Workspace_Module; Mail : aliased AWA.Mail.Module.Mail_Module; Blogs : aliased AWA.Blogs.Module.Blog_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager) is use AWA.Applications; begin ADO.Drivers.Initialize (Props); App := new AWA.Applications.Application; ASF.Tests.Initialize (Props, App.all'Access, Factory); App.Add_Filter ("service", Service_Filter'Access); App.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); declare Users : constant AWA.Users.Module.User_Module_Access := AWA.Tests.Users'Access; begin Register (App => App.all'Access, Name => AWA.Users.Module.NAME, URI => "user", Module => Users.all'Access); Register (App => App.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => App.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => App.all'Access, Name => AWA.Blogs.Module.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin App.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); WS.Register_Application ("/asfunit", App.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (App.all'Access); end; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (App.all'Access); end Set_Application_Context; end AWA.Tests;
Add the workspace module to the test application
Add the workspace module to the test application
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c254fa6e758bd58c0e5eb04ac6a9c3277fc0e796
src/gen-commands-model.adb
src/gen-commands-model.adb
----------------------------------------------------------------------- -- gen-commands-model -- Model creation command for dynamo -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Gen.Artifacts; with GNAT.Command_Line; with Gen.Utils; with Util.Files; package body Gen.Commands.Model is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Command_Line; Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Root_Dir : constant String := Generator.Get_Result_Directory; Dir : constant String := Util.Files.Compose (Root_Dir, "db"); begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Read_Project ("dynamo.xml"); Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); if Arg2'Length = 0 then -- Verify that we can use the name for an Ada identifier. if not Gen.Utils.Is_Valid_Name (Name) then Generator.Error ("The mapping name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid mapping name: " & Name; end if; Generator.Set_Global ("moduleName", ""); Generator.Set_Global ("modelName", Name); else -- Verify that we can use the name for an Ada identifier. if not Gen.Utils.Is_Valid_Name (Name) then Generator.Error ("The module name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid module name: " & Name; end if; -- Likewise for the mapping name. if not Gen.Utils.Is_Valid_Name (Arg2) then Generator.Error ("The mapping name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid mapping name: " & Arg2; end if; Generator.Set_Global ("moduleName", Name); Generator.Set_Global ("modelName", Arg2); end if; Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "add-model"); -- If the generation succeeds, run the generate command to generate the Ada files. if Generator.Get_Status = Ada.Command_Line.Success then Generator.Set_Result_Directory (Root_Dir); Generator.Set_Force_Save (True); Gen.Generator.Read_Models (Generator, "db"); -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end if; 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 ("add-model: Add a new database table model to the application"); Put_Line ("Usage: add-model [MODULE] NAME"); New_Line; Put_Line (" The database table model is an XML file that describes the mapping"); Put_Line (" for of a database table to an Ada representation."); Put_Line (" The XML description is similar to Hibernate mapping files."); Put_Line (" (See http://docs.jboss.org/hibernate/core/3.6/" & "reference/en-US/html/mapping.html)"); Put_Line (" If a MODULE is specified, the Ada package will be: " & "<PROJECT>.<MODULE>.Model.<NAME>"); Put_Line (" Otherwise, the Ada package will be: <PROJECT>.Model.<NAME>"); end Help; end Gen.Commands.Model;
----------------------------------------------------------------------- -- gen-commands-model -- Model creation command for dynamo -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Gen.Artifacts; with GNAT.Command_Line; with Gen.Utils; with Util.Files; package body Gen.Commands.Model is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name); use GNAT.Command_Line; use Ada.Command_Line; Arg1 : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else ""); Arg2 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else ""); Root_Dir : constant String := Generator.Get_Result_Directory; Dir : constant String := Util.Files.Compose (Root_Dir, "db"); begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Gen.Commands.Usage; return; end if; Generator.Read_Project ("dynamo.xml"); Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); if Args.Get_Count = 1 then -- Verify that we can use the name for an Ada identifier. if not Gen.Utils.Is_Valid_Name (Arg1) then Generator.Error ("The mapping name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid mapping name: " & Arg1; end if; Generator.Set_Global ("moduleName", ""); Generator.Set_Global ("modelName", Arg1); else -- Verify that we can use the name for an Ada identifier. if not Gen.Utils.Is_Valid_Name (Arg1) then Generator.Error ("The module name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid module name: " & Arg1; end if; -- Likewise for the mapping name. if not Gen.Utils.Is_Valid_Name (Arg2) then Generator.Error ("The mapping name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid mapping name: " & Arg2; end if; Generator.Set_Global ("moduleName", Arg1); Generator.Set_Global ("modelName", Arg2); end if; Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "add-model"); -- If the generation succeeds, run the generate command to generate the Ada files. if Generator.Get_Status = Ada.Command_Line.Success then Generator.Set_Result_Directory (Root_Dir); Generator.Set_Force_Save (True); Gen.Generator.Read_Models (Generator, "db"); -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("add-model: Add a new database table model to the application"); Put_Line ("Usage: add-model [MODULE] NAME"); New_Line; Put_Line (" The database table model is an XML file that describes the mapping"); Put_Line (" for of a database table to an Ada representation."); Put_Line (" The XML description is similar to Hibernate mapping files."); Put_Line (" (See http://docs.jboss.org/hibernate/core/3.6/" & "reference/en-US/html/mapping.html)"); Put_Line (" If a MODULE is specified, the Ada package will be: " & "<PROJECT>.<MODULE>.Model.<NAME>"); Put_Line (" Otherwise, the Ada package will be: <PROJECT>.Model.<NAME>"); end Help; end Gen.Commands.Model;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d5a40a140bb45812c93a730be43ce8658887f3a6
src/gen-model-packages.adb
src/gen-model-packages.adb
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Maps; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Util.Strings; with Util.Strings.Transforms; with Util.Log.Loggers; package body Gen.Model.Packages is use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Packages"); -- ------------------------------ -- 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 Package_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Pkg_Name); elsif Name = "package" then return Util.Beans.Objects.To_Object (From.Base_Name); elsif Name = "tables" then return From.Tables_Bean; elsif Name = "queries" then return From.Queries_Bean; elsif Name = "usedTypes" then return From.Used; elsif Name = "useCalendarTime" then return Util.Beans.Objects.To_Object (From.Uses_Calendar_Time); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Register the declaration of the given table in the model. -- ------------------------------ procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class) is begin O.Register_Package (Table.Pkg_Name, Table.Package_Def); Table.Package_Def.Tables.Append (Table.all'Access); O.Tables.Append (Table.all'Access); end Register_Table; -- ------------------------------ -- Register the declaration of the given query in the model. -- ------------------------------ procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_Definition'Class) is begin O.Register_Package (Table.Pkg_Name, Table.Package_Def); Table.Package_Def.Queries.Append (Table.all'Access); O.Queries.Append (Table.all'Access); end Register_Query; -- ------------------------------ -- Register or find the package knowing its name -- ------------------------------ procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access) is Pkg : constant String := Util.Strings.Transforms.To_Upper_Case (To_String (Name)); Key : constant Unbounded_String := To_Unbounded_String (Pkg); Pos : constant Package_Map.Cursor := O.Packages.Find (Key); begin if not Package_Map.Has_Element (Pos) then declare Map : Ada.Strings.Maps.Character_Mapping; Base_Name : Unbounded_String; begin Map := Ada.Strings.Maps.To_Mapping (From => ".", To => "-"); Base_Name := Translate (Name, Map); Result := new Package_Definition; Result.Pkg_Name := Name; Result.Tables_Bean := Util.Beans.Objects.To_Object (Result.Tables'Access, Util.Beans.Objects.STATIC); Util.Strings.Transforms.To_Lower_Case (To_String (Base_Name), Result.Base_Name); O.Packages.Insert (Key, Result); Log.Debug ("Ada package '{0}' registered", Name); end; else Result := Package_Map.Element (Pos); end if; end Register_Package; -- ------------------------------ -- Returns True if the model contains at least one package. -- ------------------------------ function Has_Packages (O : in Model_Definition) return Boolean is begin return not O.Packages.Is_Empty; end Has_Packages; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Package_Definition) is use Gen.Model.Tables; procedure Prepare_Table (Table : in Table_Definition_Access); procedure Prepare_Tables (Tables : in Table_List.List_Definition); Used_Types : Gen.Utils.String_Set.Set; T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Used_Types'Unchecked_Access; procedure Prepare_Table (Table : in Table_Definition_Access) is C : Column_List.Cursor := Table.Members.First; begin Table.Prepare; -- Walk the columns to get their type. while Column_List.Has_Element (C) loop declare Col : constant Column_Definition_Access := Column_List.Element (C); T : constant String := To_String (Col.Type_Name); Name : constant String := Gen.Utils.Get_Package_Name (T); begin if not Col.Is_Basic_Type and Name'Length > 0 then Used_Types.Include (To_Unbounded_String (Name)); elsif T = "Time" or T = "Date" or T = "Timestamp" or T = "Nullable_Time" then O.Uses_Calendar_Time := True; end if; end; Column_List.Next (C); end loop; end Prepare_Table; procedure Prepare_Tables (Tables : in Table_List.List_Definition) is Table_Iter : Table_List.Cursor := Tables.First; begin while Table_List.Has_Element (Table_Iter) loop declare Table : constant Table_Definition_Access := Table_Definition_Access (Table_List.Element (Table_Iter)); begin Prepare_Table (Table); end; Table_List.Next (Table_Iter); end loop; end Prepare_Tables; begin O.Used := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Used_Types.Row := 0; O.Used_Types.Values.Clear; O.Uses_Calendar_Time := False; Prepare_Tables (O.Tables); Prepare_Tables (O.Queries); declare P : Gen.Utils.String_Set.Cursor := Used_Types.First; begin while Gen.Utils.String_Set.Has_Element (P) loop declare Name : constant Unbounded_String := Gen.Utils.String_Set.Element (P); begin Log.Info ("with {0}", Name); O.Used_Types.Values.Append (Util.Beans.Objects.To_Object (Name)); end; Gen.Utils.String_Set.Next (P); end loop; end; end Prepare; -- ------------------------------ -- Initialize the package instance -- ------------------------------ overriding procedure Initialize (O : in out Package_Definition) is use Util.Beans.Objects; begin O.Tables_Bean := Util.Beans.Objects.To_Object (O.Tables'Unchecked_Access, STATIC); O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access, STATIC); O.Used := Util.Beans.Objects.To_Object (O.Used_Types'Unchecked_Access, STATIC); end Initialize; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : List_Object) return Natural is begin Log.Debug ("Length {0}", Natural'Image (Natural (From.Values.Length))); return Natural (From.Values.Length); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural) is begin Log.Debug ("Setting row {0}", Natural'Image (Index)); From.Row := Index; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : List_Object) return Util.Beans.Objects.Object is begin Log.Debug ("Getting row {0}", Natural'Image (From.Row)); return From.Values.Element (From.Row - 1); end Get_Row; -- ------------------------------ -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); pragma Unreferenced (Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Model_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tables" then return From.Tables_Bean; elsif Name = "dirname" then return Util.Beans.Objects.To_Object (From.Dir_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. -- ------------------------------ procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String) is begin O.Dir_Name := To_Unbounded_String (Target_Dir); O.DB_Name := To_Unbounded_String (Model_Dir); end Set_Dirname; -- ------------------------------ -- Get the directory name associated with the model. -- ------------------------------ function Get_Dirname (O : in Model_Definition) return String is begin return To_String (O.Dir_Name); end Get_Dirname; -- ------------------------------ -- Get the directory name which contains the model. -- ------------------------------ function Get_Model_Directory (O : in Model_Definition) return String is begin return To_String (O.DB_Name); end Get_Model_Directory; -- ------------------------------ -- Initialize the model definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Model_Definition) is T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Tables'Unchecked_Access; begin O.Tables_Bean := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Dir_Name := To_Unbounded_String ("src"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Model_Definition) is Iter : Package_Cursor := O.Packages.First; begin while Has_Element (Iter) loop Element (Iter).Prepare; Next (Iter); end loop; end Prepare; -- ------------------------------ -- Get the first package of the model definition. -- ------------------------------ function First (From : Model_Definition) return Package_Cursor is begin return From.Packages.First; end First; -- ------------------------------ -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. -- ------------------------------ procedure Register_Type (O : in out Model_Definition; From : in String; To : in String) is begin null; end Register_Type; end Gen.Model.Packages;
----------------------------------------------------------------------- -- gen-model-packages -- Packages holding model, query representation -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Maps; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Util.Strings; with Util.Strings.Transforms; with Util.Log.Loggers; package body Gen.Model.Packages is use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Packages"); -- ------------------------------ -- 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 Package_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Pkg_Name); elsif Name = "package" then return Util.Beans.Objects.To_Object (From.Base_Name); elsif Name = "tables" then return From.Tables_Bean; elsif Name = "queries" then return From.Queries_Bean; elsif Name = "usedTypes" then return From.Used; elsif Name = "useCalendarTime" then return Util.Beans.Objects.To_Object (From.Uses_Calendar_Time); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Register the declaration of the given table in the model. -- ------------------------------ procedure Register_Table (O : in out Model_Definition; Table : access Gen.Model.Tables.Table_Definition'Class) is begin O.Register_Package (Table.Pkg_Name, Table.Package_Def); Table.Package_Def.Tables.Append (Table.all'Access); O.Tables.Append (Table.all'Access); end Register_Table; -- ------------------------------ -- Register the declaration of the given query in the model. -- ------------------------------ procedure Register_Query (O : in out Model_Definition; Table : access Gen.Model.Queries.Query_Definition'Class) is begin O.Register_Package (Table.Pkg_Name, Table.Package_Def); Table.Package_Def.Queries.Append (Table.all'Access); O.Queries.Append (Table.all'Access); end Register_Query; -- ------------------------------ -- Register or find the package knowing its name -- ------------------------------ procedure Register_Package (O : in out Model_Definition; Name : in Unbounded_String; Result : out Package_Definition_Access) is Pkg : constant String := Util.Strings.Transforms.To_Upper_Case (To_String (Name)); Key : constant Unbounded_String := To_Unbounded_String (Pkg); Pos : constant Package_Map.Cursor := O.Packages.Find (Key); begin if not Package_Map.Has_Element (Pos) then declare Map : Ada.Strings.Maps.Character_Mapping; Base_Name : Unbounded_String; begin Map := Ada.Strings.Maps.To_Mapping (From => ".", To => "-"); Base_Name := Translate (Name, Map); Result := new Package_Definition; Result.Pkg_Name := Name; Result.Tables_Bean := Util.Beans.Objects.To_Object (Result.Tables'Access, Util.Beans.Objects.STATIC); Util.Strings.Transforms.To_Lower_Case (To_String (Base_Name), Result.Base_Name); O.Packages.Insert (Key, Result); Log.Debug ("Ada package '{0}' registered", Name); end; else Result := Package_Map.Element (Pos); end if; end Register_Package; -- ------------------------------ -- Returns True if the model contains at least one package. -- ------------------------------ function Has_Packages (O : in Model_Definition) return Boolean is begin return not O.Packages.Is_Empty; end Has_Packages; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Package_Definition) is use Gen.Model.Tables; procedure Prepare_Table (Table : in Table_Definition_Access); procedure Prepare_Tables (Tables : in Table_List.List_Definition); Used_Types : Gen.Utils.String_Set.Set; T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Used_Types'Unchecked_Access; procedure Prepare_Table (Table : in Table_Definition_Access) is C : Column_List.Cursor := Table.Members.First; begin Table.Prepare; -- Walk the columns to get their type. while Column_List.Has_Element (C) loop declare Col : constant Column_Definition_Access := Column_List.Element (C); T : constant String := To_String (Col.Type_Name); Name : constant String := Gen.Utils.Get_Package_Name (T); begin if not Col.Is_Basic_Type and Name'Length > 0 and Name /= O.Pkg_Name then Used_Types.Include (To_Unbounded_String (Name)); elsif T = "Time" or T = "Date" or T = "Timestamp" or T = "Nullable_Time" then O.Uses_Calendar_Time := True; end if; end; Column_List.Next (C); end loop; end Prepare_Table; procedure Prepare_Tables (Tables : in Table_List.List_Definition) is Table_Iter : Table_List.Cursor := Tables.First; begin while Table_List.Has_Element (Table_Iter) loop declare Table : constant Table_Definition_Access := Table_Definition_Access (Table_List.Element (Table_Iter)); begin Prepare_Table (Table); end; Table_List.Next (Table_Iter); end loop; end Prepare_Tables; begin Log.Info ("Preparing package {0}", O.Pkg_Name); O.Used := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Used_Types.Row := 0; O.Used_Types.Values.Clear; O.Uses_Calendar_Time := False; Prepare_Tables (O.Tables); Prepare_Tables (O.Queries); declare P : Gen.Utils.String_Set.Cursor := Used_Types.First; begin while Gen.Utils.String_Set.Has_Element (P) loop declare Name : constant Unbounded_String := Gen.Utils.String_Set.Element (P); begin Log.Info ("with {0}", Name); O.Used_Types.Values.Append (Util.Beans.Objects.To_Object (Name)); end; Gen.Utils.String_Set.Next (P); end loop; end; end Prepare; -- ------------------------------ -- Initialize the package instance -- ------------------------------ overriding procedure Initialize (O : in out Package_Definition) is use Util.Beans.Objects; begin O.Tables_Bean := Util.Beans.Objects.To_Object (O.Tables'Unchecked_Access, STATIC); O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access, STATIC); O.Used := Util.Beans.Objects.To_Object (O.Used_Types'Unchecked_Access, STATIC); end Initialize; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : List_Object) return Natural is begin Log.Debug ("Length {0}", Natural'Image (Natural (From.Values.Length))); return Natural (From.Values.Length); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out List_Object; Index : in Natural) is begin Log.Debug ("Setting row {0}", Natural'Image (Index)); From.Row := Index; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : List_Object) return Util.Beans.Objects.Object is begin Log.Debug ("Getting row {0}", Natural'Image (From.Row)); return From.Values.Element (From.Row - 1); end Get_Row; -- ------------------------------ -- 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 List_Object; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From); pragma Unreferenced (Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Model_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "tables" then return From.Tables_Bean; elsif Name = "dirname" then return Util.Beans.Objects.To_Object (From.Dir_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the directory name associated with the model. This directory name allows to -- save and build a model in separate directories for the application, the unit tests -- and others. -- ------------------------------ procedure Set_Dirname (O : in out Model_Definition; Target_Dir : in String; Model_Dir : in String) is begin O.Dir_Name := To_Unbounded_String (Target_Dir); O.DB_Name := To_Unbounded_String (Model_Dir); end Set_Dirname; -- ------------------------------ -- Get the directory name associated with the model. -- ------------------------------ function Get_Dirname (O : in Model_Definition) return String is begin return To_String (O.Dir_Name); end Get_Dirname; -- ------------------------------ -- Get the directory name which contains the model. -- ------------------------------ function Get_Model_Directory (O : in Model_Definition) return String is begin return To_String (O.DB_Name); end Get_Model_Directory; -- ------------------------------ -- Initialize the model definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Model_Definition) is T : constant Util.Beans.Basic.Readonly_Bean_Access := O.Tables'Unchecked_Access; begin O.Tables_Bean := Util.Beans.Objects.To_Object (T, Util.Beans.Objects.STATIC); O.Dir_Name := To_Unbounded_String ("src"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (O : in out Model_Definition) is Iter : Package_Cursor := O.Packages.First; begin while Has_Element (Iter) loop Element (Iter).Prepare; Next (Iter); end loop; end Prepare; -- ------------------------------ -- Get the first package of the model definition. -- ------------------------------ function First (From : Model_Definition) return Package_Cursor is begin return From.Packages.First; end First; -- ------------------------------ -- Register a type mapping. The <b>From</b> type describes a type in the XML -- configuration files (hibernate, query, ...) and the <b>To</b> represents the -- corresponding Ada type. -- ------------------------------ procedure Register_Type (O : in out Model_Definition; From : in String; To : in String) is begin null; end Register_Type; end Gen.Model.Packages;
Fix circular dependency of generated code - if the XML model definition has <many-to-one> relation that refer to the current package name, make sure the package name is not part of the 'with' clause list.
Fix circular dependency of generated code - if the XML model definition has <many-to-one> relation that refer to the current package name, make sure the package name is not part of the 'with' clause list.
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo