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
6aa43aa7b293e23786d436bb702a10bcf0b6d39f
src/http/curl/util-http-clients-curl.ads
src/http/curl/util-http-clients-curl.ads
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- with System; with Interfaces.C; with Interfaces.C.Strings; with Ada.Strings.Unbounded; with Util.Http.Mockups; package Util.Http.Clients.Curl is -- Register the CURL Http manager. procedure Register; private package C renames Interfaces.C; package Strings renames Interfaces.C.Strings; use type C.size_t; use type C.int; -- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due -- to Eclipse capitalization. subtype Int is C.int; subtype Chars_Ptr is Strings.chars_ptr; subtype Size_T is C.size_t; subtype CURL is System.Address; type CURL_Code is new Interfaces.C.int; CURLE_OK : constant CURL_Code := 0; type CURL_Info is new Int; type Curl_Option is new Int; type CURL_Slist; type CURL_Slist_Access is access CURL_Slist; type CURL_Slist is record Data : Chars_Ptr; Next : CURL_Slist_Access; end record; -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. procedure Check_Code (Code : in CURL_Code; Message : in String); type Curl_Http_Manager is new Http_Manager with null record; type Curl_Http_Manager_Access is access all Http_Manager'Class; -- Create a new HTTP request associated with the current request manager. procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class); overriding procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); overriding procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); -- Set the timeout for the connection. overriding procedure Set_Timeout (Manager : in Curl_Http_Manager; Http : in Client'Class; Timeout : in Duration); type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record Data : CURL := System.Null_Address; URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Curl_Headers : CURL_Slist_Access := null; end record; type Curl_Http_Request_Access is access all Curl_Http_Request'Class; -- Prepare to setup the headers in the request. procedure Set_Headers (Request : in out Curl_Http_Request); overriding procedure Finalize (Request : in out Curl_Http_Request); type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record C : CURL; Content : Ada.Strings.Unbounded.Unbounded_String; Status : Natural; Parsing_Body : Boolean := False; end record; type Curl_Http_Response_Access is access all Curl_Http_Response'Class; -- Get the response body as a string. overriding function Get_Body (Reply : in Curl_Http_Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Curl_Http_Response) return Natural; -- Add a string to a CURL slist. function Curl_Slist_Append (List : in CURL_Slist_Access; Value : in Chars_Ptr) return CURL_Slist_Access; pragma Import (C, Curl_Slist_Append, "curl_slist_append"); -- Free an entrire CURL slist. procedure Curl_Slist_Free_All (List : in CURL_Slist_Access); pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all"); -- Start a libcurl easy session. function Curl_Easy_Init return CURL; pragma Import (C, Curl_Easy_Init, "curl_easy_init"); -- End a libcurl easy session. procedure Curl_Easy_Cleanup (Handle : in CURL); pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup"); -- Perform a file transfer. function Curl_Easy_Perform (Handle : in CURL) return CURL_Code; pragma Import (C, Curl_Easy_Perform, "curl_easy_perform"); -- Return the error message which correspond to the given CURL error code. function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr; pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_String (Handle : in CURL; Option : in Curl_Option; Value : in Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Slist (Handle : in CURL; Option : in Curl_Option; Value : in CURL_Slist_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Long (Handle : in CURL; Option : in Curl_Option; Value : in Interfaces.C.long) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt"); -- Get information from a CURL handle for an option returning a String. function Curl_Easy_Getinfo_String (Handle : in CURL; Option : in CURL_Info; Value : access Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo"); -- Get information from a CURL handle for an option returning a Long. function Curl_Easy_Getinfo_Long (Handle : in CURL; Option : in CURL_Info; Value : access C.long) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo"); function Curl_Easy_Setopt_Write_Callback (Handle : in CURL; Option : in Curl_Option; Func : access function (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Ptr : in Curl_Http_Response_Access) return Size_T) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Data (Handle : in CURL; Option : in Curl_Option; Value : in Curl_Http_Response_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt"); function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T; end Util.Http.Clients.Curl;
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- with System; with Interfaces.C; with Interfaces.C.Strings; with Ada.Strings.Unbounded; with Util.Http.Mockups; package Util.Http.Clients.Curl is -- Register the CURL Http manager. procedure Register; private package C renames Interfaces.C; package Strings renames Interfaces.C.Strings; use type C.size_t; use type C.int; -- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due -- to Eclipse capitalization. subtype Int is C.int; subtype Chars_Ptr is Strings.chars_ptr; subtype Size_T is C.size_t; subtype CURL is System.Address; type CURL_Code is new Interfaces.C.int; CURLE_OK : constant CURL_Code := 0; type CURL_Info is new Int; type Curl_Option is new Int; type CURL_Slist; type CURL_Slist_Access is access CURL_Slist; type CURL_Slist is record Data : Chars_Ptr; Next : CURL_Slist_Access; end record; -- Check the CURL result code and report and exception and a log message if -- the CURL code indicates an error. procedure Check_Code (Code : in CURL_Code; Message : in String); type Curl_Http_Manager is new Http_Manager with null record; type Curl_Http_Manager_Access is access all Http_Manager'Class; -- Create a new HTTP request associated with the current request manager. procedure Create (Manager : in Curl_Http_Manager; Http : in out Client'Class); overriding procedure Do_Get (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class); overriding procedure Do_Post (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); overriding procedure Do_Put (Manager : in Curl_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class); -- Set the timeout for the connection. overriding procedure Set_Timeout (Manager : in Curl_Http_Manager; Http : in Client'Class; Timeout : in Duration); type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record Data : CURL := System.Null_Address; URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr; Curl_Headers : CURL_Slist_Access := null; end record; type Curl_Http_Request_Access is access all Curl_Http_Request'Class; -- Prepare to setup the headers in the request. procedure Set_Headers (Request : in out Curl_Http_Request); overriding procedure Finalize (Request : in out Curl_Http_Request); type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record C : CURL; Content : Ada.Strings.Unbounded.Unbounded_String; Status : Natural; Parsing_Body : Boolean := False; end record; type Curl_Http_Response_Access is access all Curl_Http_Response'Class; -- Get the response body as a string. overriding function Get_Body (Reply : in Curl_Http_Response) return String; -- Get the response status code. overriding function Get_Status (Reply : in Curl_Http_Response) return Natural; -- Add a string to a CURL slist. function Curl_Slist_Append (List : in CURL_Slist_Access; Value : in Chars_Ptr) return CURL_Slist_Access; pragma Import (C, Curl_Slist_Append, "curl_slist_append"); -- Free an entrire CURL slist. procedure Curl_Slist_Free_All (List : in CURL_Slist_Access); pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all"); -- Start a libcurl easy session. function Curl_Easy_Init return CURL; pragma Import (C, Curl_Easy_Init, "curl_easy_init"); -- End a libcurl easy session. procedure Curl_Easy_Cleanup (Handle : in CURL); pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup"); -- Perform a file transfer. function Curl_Easy_Perform (Handle : in CURL) return CURL_Code; pragma Import (C, Curl_Easy_Perform, "curl_easy_perform"); -- Return the error message which correspond to the given CURL error code. function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr; pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_String (Handle : in CURL; Option : in Curl_Option; Value : in Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Slist (Handle : in CURL; Option : in Curl_Option; Value : in CURL_Slist_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Slist, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Long (Handle : in CURL; Option : in Curl_Option; Value : in Interfaces.C.long) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt"); -- Get information from a CURL handle for an option returning a String. function Curl_Easy_Getinfo_String (Handle : in CURL; Option : in CURL_Info; Value : access Chars_Ptr) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo"); -- Get information from a CURL handle for an option returning a Long. function Curl_Easy_Getinfo_Long (Handle : in CURL; Option : in CURL_Info; Value : access C.long) return CURL_Code; pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo"); function Curl_Easy_Setopt_Write_Callback (Handle : in CURL; Option : in Curl_Option; Func : access function (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Ptr : in Curl_Http_Response_Access) return Size_T) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt"); -- Set options for a curl easy handle. function Curl_Easy_Setopt_Data (Handle : in CURL; Option : in Curl_Option; Value : in Curl_Http_Response_Access) return CURL_Code; pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt"); function Read_Response (Data : in Chars_Ptr; Size : in Size_T; Nmemb : in Size_T; Response : in Curl_Http_Response_Access) return Size_T; pragma Convention (C, Read_Response); end Util.Http.Clients.Curl;
Add missing Convention pragma for the Read_Response procedure
Add missing Convention pragma for the Read_Response procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ef920497032e09511241b0099907af818daaafe8
src/natools-web-acl-sx_backends.adb
src/natools-web-acl-sx_backends.adb
------------------------------------------------------------------------------ -- Copyright (c) 2017-2019, 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.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; package body Natools.Web.ACL.Sx_Backends is type User_Builder is record Tokens, Groups : Containers.Unsafe_Atom_Lists.List; end record; type Backend_Builder is record Map : Token_Maps.Unsafe_Maps.Map; end record; Cookie_Name : constant String := "User-Token"; procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Read_DB is new S_Expressions.Interpreter_Loop (Backend_Builder, Meaningless_Type, Process_User); procedure Read_User is new S_Expressions.Interpreter_Loop (User_Builder, Meaningless_Type, Process_User_Element); -------------------------- -- Constructor Elements -- -------------------------- procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); User : User_Builder; Identity : Containers.Identity; begin Read_User (Arguments, User, Meaningless_Value); Identity := (User => S_Expressions.Atom_Ref_Constructors.Create (Name), Groups => Containers.Create (User.Groups)); for Token of User.Tokens loop Builder.Map.Include (Token, Identity); end loop; end Process_User; procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); S_Name : constant String := S_Expressions.To_String (Name); begin if S_Name = "tokens" or else S_Name = "token" then Containers.Append_Atoms (Builder.Tokens, Arguments); elsif S_Name = "groups" or else S_Name = "group" then Containers.Append_Atoms (Builder.Groups, Arguments); else Log (Severities.Error, "Unknown user element """ & S_Name & '"'); end if; end Process_User_Element; ---------------------- -- Public Interface -- ---------------------- overriding procedure Authenticate (Self : in Backend; Exchange : in out Exchanges.Exchange) is Cursor : constant Token_Maps.Cursor := Self.Map.Find (S_Expressions.To_Atom (Exchange.Cookie (Cookie_Name))); Identity : Containers.Identity; begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; Exchange.Set_Identity (Identity); end Authenticate; function Create (Arguments : in out S_Expressions.Lockable.Descriptor'Class) return ACL.Backend'Class is Builder : Backend_Builder; begin case Arguments.Current_Event is when S_Expressions.Events.Open_List => Read_DB (Arguments, Builder, Meaningless_Value); when S_Expressions.Events.Add_Atom => declare Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Arguments.Current_Atom)); begin Read_DB (Reader, Builder, Meaningless_Value); end; when others => Log (Severities.Error, "Unable to create ACL from S-expression" & " starting with " & Arguments.Current_Event'Img); end case; return Backend'(Map => Token_Maps.Create (Builder.Map), Hashed => <>); end Create; procedure Register (Id : in Character; Fn : in Hash_Function) is begin if Fn = null then null; elsif Hash_Function_DB.Is_Empty then Hash_Function_DB.Replace (new Hash_Function_Array'(Id => Fn)); elsif Id in Hash_Function_DB.Query.Data.all'Range then Hash_Function_DB.Update.Data.all (Id) := Fn; else declare New_First : constant Hash_Id := Hash_Id'Min (Id, Hash_Function_DB.Query.Data.all'First); New_Last : constant Hash_Id := Hash_Id'Max (Id, Hash_Function_DB.Query.Data.all'Last); New_Data : constant Hash_Function_Array_Refs.Data_Access := new Hash_Function_Array'(New_First .. New_Last => null); begin New_Data (Hash_Function_DB.Query.Data.all'First .. Hash_Function_DB.Query.Data.all'Last) := Hash_Function_DB.Query.Data.all; Hash_Function_DB.Replace (New_Data); end; end if; end Register; end Natools.Web.ACL.Sx_Backends;
------------------------------------------------------------------------------ -- Copyright (c) 2017-2019, 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.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; package body Natools.Web.ACL.Sx_Backends is type User_Builder is record Tokens, Groups : Containers.Unsafe_Atom_Lists.List; end record; type Backend_Builder is record Map : Token_Maps.Unsafe_Maps.Map; end record; Cookie_Name : constant String := "User-Token"; Hash_Mark : constant Character := '$'; procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class); procedure Read_DB is new S_Expressions.Interpreter_Loop (Backend_Builder, Meaningless_Type, Process_User); procedure Read_User is new S_Expressions.Interpreter_Loop (User_Builder, Meaningless_Type, Process_User_Element); -------------------------- -- Constructor Elements -- -------------------------- procedure Process_User (Builder : in out Backend_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); User : User_Builder; Identity : Containers.Identity; begin Read_User (Arguments, User, Meaningless_Value); Identity := (User => S_Expressions.Atom_Ref_Constructors.Create (Name), Groups => Containers.Create (User.Groups)); for Token of User.Tokens loop Builder.Map.Include (Token, Identity); end loop; end Process_User; procedure Process_User_Element (Builder : in out User_Builder; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); S_Name : constant String := S_Expressions.To_String (Name); begin if S_Name = "tokens" or else S_Name = "token" then Containers.Append_Atoms (Builder.Tokens, Arguments); elsif S_Name = "groups" or else S_Name = "group" then Containers.Append_Atoms (Builder.Groups, Arguments); else Log (Severities.Error, "Unknown user element """ & S_Name & '"'); end if; end Process_User_Element; ---------------------- -- Public Interface -- ---------------------- overriding procedure Authenticate (Self : in Backend; Exchange : in out Exchanges.Exchange) is Cookie : constant String := Exchange.Cookie (Cookie_Name); Identity : Containers.Identity; begin if Cookie'Length > 3 and then Cookie (Cookie'First) = Hash_Mark and then Cookie (Cookie'First + 2) = Hash_Mark and then not Self.Hashed.Is_Empty and then Cookie (Cookie'First + 1) in Self.Hashed.Query.Data.all'Range then declare Token : constant S_Expressions.Atom := S_Expressions.To_Atom (Cookie (Cookie'First + 3 .. Cookie'Last)); Hash : constant S_Expressions.Atom := Hash_Function_DB.Query.Data (Cookie (Cookie'First + 1)).all (Token); Cursor : constant Token_Maps.Cursor := Self.Hashed.Query.Data (Cookie (Cookie'First + 1)).Find (Hash); begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; end; else declare Cursor : constant Token_Maps.Cursor := Self.Map.Find (S_Expressions.To_Atom (Cookie)); begin if Token_Maps.Has_Element (Cursor) then Identity := Token_Maps.Element (Cursor); end if; end; end if; Exchange.Set_Identity (Identity); end Authenticate; function Create (Arguments : in out S_Expressions.Lockable.Descriptor'Class) return ACL.Backend'Class is Builder : Backend_Builder; begin case Arguments.Current_Event is when S_Expressions.Events.Open_List => Read_DB (Arguments, Builder, Meaningless_Value); when S_Expressions.Events.Add_Atom => declare Reader : S_Expressions.File_Readers.S_Reader := S_Expressions.File_Readers.Reader (S_Expressions.To_String (Arguments.Current_Atom)); begin Read_DB (Reader, Builder, Meaningless_Value); end; when others => Log (Severities.Error, "Unable to create ACL from S-expression" & " starting with " & Arguments.Current_Event'Img); end case; return Backend'(Map => Token_Maps.Create (Builder.Map), Hashed => <>); end Create; procedure Register (Id : in Character; Fn : in Hash_Function) is begin if Fn = null then null; elsif Hash_Function_DB.Is_Empty then Hash_Function_DB.Replace (new Hash_Function_Array'(Id => Fn)); elsif Id in Hash_Function_DB.Query.Data.all'Range then Hash_Function_DB.Update.Data.all (Id) := Fn; else declare New_First : constant Hash_Id := Hash_Id'Min (Id, Hash_Function_DB.Query.Data.all'First); New_Last : constant Hash_Id := Hash_Id'Max (Id, Hash_Function_DB.Query.Data.all'Last); New_Data : constant Hash_Function_Array_Refs.Data_Access := new Hash_Function_Array'(New_First .. New_Last => null); begin New_Data (Hash_Function_DB.Query.Data.all'First .. Hash_Function_DB.Query.Data.all'Last) := Hash_Function_DB.Query.Data.all; Hash_Function_DB.Replace (New_Data); end; end if; end Register; end Natools.Web.ACL.Sx_Backends;
use hashed tokens to authenticate
acl-sx_backends: use hashed tokens to authenticate
Ada
isc
faelys/natools-web,faelys/natools-web
3c78809d7a2b92fcf7a872bcd3e7b263025ee5d9
src/util-commands-consoles-text.ads
src/util-commands-consoles-text.ads
----------------------------------------------------------------------- -- util-commands-consoles-text - Text console interface -- Copyright (C) 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; generic package Util.Commands.Consoles.Text is type Console_Type is new Util.Commands.Consoles.Console_Type with private; -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String); -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String); -- Print the field value for the given field. overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT); -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String); -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type); -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type); -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type); -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type); private type Console_Type is new Util.Commands.Consoles.Console_Type with record File : Ada.Text_IO.File_Type; end record; end Util.Commands.Consoles.Text;
----------------------------------------------------------------------- -- util-commands-consoles-text -- Text console interface -- Copyright (C) 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; generic package Util.Commands.Consoles.Text is type Console_Type is new Util.Commands.Consoles.Console_Type with private; -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String); -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String); -- Print the field value for the given field. overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String; Justify : in Justify_Type := J_LEFT); -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String); -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type); -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type); -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type); -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type); private type Console_Type is new Util.Commands.Consoles.Console_Type with record File : Ada.Text_IO.File_Type; end record; end Util.Commands.Consoles.Text;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
15e3c6a611b0ee244fd32bc3ed882b5471e9cfae
testutil/ahven/ahven-xml_runner.adb
testutil/ahven/ahven-xml_runner.adb
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Trim (Get_Message (Info), Ada.Strings.Both)); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
Fix other issues when a message contains unclosed XML entities.
Fix other issues when a message contains unclosed XML entities.
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5e242e0b86ca547d89717d3a62e65455fc6ec8b8
regtests/ado-tests.adb
regtests/ado-tests.adb
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); 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; T.Fail ("Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.Session_Error => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.Session_Error => 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); 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 type ADO.Sessions.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (DB.Get_Status = ADO.Sessions.OPEN, "The database connection is open"); 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 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); 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; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Nullable_String; begin Name.Is_Null := False; for I in 1 .. 127 loop Append (Name.Value, Character'Val (I)); end loop; Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name.Value), String '(Usr2.Get_Name), "Invalid name inserted for user"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); declare Content : Ada.Streams.Stream_Element_Array (1 .. 10); Img3 : Regtests.Images.Model.Image_Ref; begin for I in Content'Range loop Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30); end loop; Data := ADO.Create_Blob (Content); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)"); T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small"); DB.Begin_Transaction; Img3.Set_Image (Data); Img3.Set_Create_Date (Ada.Calendar.Clock); Img3.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img3.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); Img2.Set_Image (ADO.Null_Blob); Img2.Save (DB); DB.Commit; end; end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
----------------------------------------------------------------------- -- ADO Sequences -- Database sequence generator -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Calendar; with ADO.Statements; with ADO.Objects; with ADO.Sessions; with ADO.Utils; with Regtests; with Regtests.Simple.Model; with Regtests.Images.Model; with Util.Assertions; with Util.Measures; with Util.Log; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Test_Caller; package body ADO.Tests is use Ada.Exceptions; use ADO.Statements; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Tests"); package Caller is new Util.Test_Caller (Test, "ADO"); procedure Assert_Has_Message (T : in Test; E : in Exception_Occurrence); 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; T.Fail ("Master_Connection.Rollback should raise an exception"); exception when E : ADO.Sessions.Session_Error => Assert_Has_Message (T, E); end; begin DB.Commit; T.Fail ("Master_Connection.Commit should raise an exception"); exception when E : ADO.Sessions.Session_Error => 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); 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 type ADO.Sessions.Connection_Status; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Ref : Regtests.Simple.Model.Allocate_Ref; Ref2 : Regtests.Simple.Model.Allocate_Ref; begin T.Assert (DB.Get_Status = ADO.Sessions.OPEN, "The database connection is open"); 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 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); 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; -- ------------------------------ -- Test string insert. -- ------------------------------ procedure Test_String (T : in out Test) is use Ada.Strings.Unbounded; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; User : Regtests.Simple.Model.User_Ref; Usr2 : Regtests.Simple.Model.User_Ref; Name : Nullable_String; begin Name.Is_Null := False; for I in 1 .. 127 loop Append (Name.Value, Character'Val (I)); end loop; Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); Append (Name.Value, ' '); DB.Begin_Transaction; User.Set_Name (Name); User.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Usr2.Load (DB, User.Get_Id); Util.Tests.Assert_Equals (T, To_String (Name.Value), String '(Usr2.Get_Name), "Invalid name inserted for user"); Usr2.Set_Name (ADO.Null_String); Usr2.Save (DB); User.Load (DB, Usr2.Get_Id); T.Assert (User.Get_Name.Is_Null, "Name must be null after save"); end Test_String; -- ------------------------------ -- Test blob insert. -- ------------------------------ procedure Test_Blob (T : in out Test) is use Ada.Streams; procedure Assert_Equals is new Util.Assertions.Assert_Equals_T (Ada.Streams.Stream_Element); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Img : Regtests.Images.Model.Image_Ref; Size : constant Natural := 100; Data : ADO.Blob_Ref := ADO.Create_Blob (Size); Img2 : Regtests.Images.Model.Image_Ref; begin for I in 1 .. Size loop Data.Value.Data (Ada.Streams.Stream_Element_Offset (I)) := Integer'Pos ((64 + I) mod 255); end loop; DB.Begin_Transaction; Img.Set_Image (Data); Img.Set_Create_Date (Ada.Calendar.Clock); Img.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); -- And verify that the blob data matches what we inserted. Util.Tests.Assert_Equals (T, Size, Integer (Img2.Get_Image.Value.Len), "Invalid blob length"); for I in 1 .. Data.Value.Len loop Assert_Equals (T, Data.Value.Data (I), Img2.Get_Image.Value.Data (I), "Invalid blob content at " & Stream_Element_Offset'Image (I)); end loop; -- Create a blob initialized with a file content. Data := ADO.Create_Blob ("Makefile"); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob"); T.Assert (Data.Value.Len > 100, "Blob length initialized from file is too small"); declare Content : Ada.Streams.Stream_Element_Array (1 .. 10); Img3 : Regtests.Images.Model.Image_Ref; begin for I in Content'Range loop Content (I) := Ada.Streams.Stream_Element_Offset'Pos (I + 30); end loop; Data := ADO.Create_Blob (Content); T.Assert (not Data.Is_Null, "Null blob returned by Create_Blob (Stream_Element_Array)"); T.Assert (Data.Value.Len = 10, "Blob length initialized from array is too small"); DB.Begin_Transaction; Img3.Set_Image (Data); Img3.Set_Create_Date (Ada.Calendar.Clock); Img3.Save (DB); DB.Commit; -- Check that we can load the image and the blob. Img2.Load (DB, Img3.Get_Id); T.Assert (Img2.Get_Image.Is_Null = False, "No image blob loaded"); Img2.Set_Image (ADO.Null_Blob); Img2.Save (DB); DB.Commit; end; end Test_Blob; -- ------------------------------ -- Test the To_Object and To_Identifier operations. -- ------------------------------ procedure Test_Identifier_To_Object (T : in out Test) is Val : Util.Beans.Objects.Object := ADO.Utils.To_Object (ADO.NO_IDENTIFIER); begin T.Assert (Util.Beans.Objects.Is_Null (Val), "To_Object must return null for ADO.NO_IDENTIFIER"); T.Assert (ADO.Utils.To_Identifier (Val) = ADO.NO_IDENTIFIER, "To_Identifier must return ADO.NO_IDENTIFIER for null"); Val := ADO.Utils.To_Object (1); T.Assert (not Util.Beans.Objects.Is_Null (Val), "To_Object must not return null for a valid Identifier"); T.Assert (ADO.Utils.To_Identifier (Val) = 1, "To_Identifier must return the correct identifier"); end Test_Identifier_To_Object; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Object_Ref.Load", Test_Load'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save", Test_Create_Load'Access); Caller.Add_Test (Suite, "Test Master_Connection init error", Test_Not_Open'Access); Caller.Add_Test (Suite, "Test Sequences.Factory", Test_Allocate'Access); Caller.Add_Test (Suite, "Test Object_Ref.Save/Create/Update", Test_Create_Save'Access); Caller.Add_Test (Suite, "Test Object_Ref.Create (DB Insert)", Test_Perf_Create_Save'Access); Caller.Add_Test (Suite, "Test Statement.Delete_Statement (delete all)", Test_Delete_All'Access); Caller.Add_Test (Suite, "Test insert string", Test_String'Access); Caller.Add_Test (Suite, "Test insert blob", Test_Blob'Access); Caller.Add_Test (Suite, "Test ADO.Utils.To_Object/To_Identifier", Test_Identifier_To_Object'Access); end Add_Tests; end ADO.Tests;
Update Test_String to cover setting a string back to null
Update Test_String to cover setting a string back to null
Ada
apache-2.0
stcarrez/ada-ado
62073a6643cb9a45f68cbf0ca0ee14a0d4e235da
awa/src/awa-applications-configs.ads
awa/src/awa-applications-configs.ads
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration 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 EL.Contexts.Default; with Util.Serialize.IO.XML; -- The <b>AWA.Applications.Configs</b> package reads the application configuration files. package AWA.Applications.Configs is -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. generic Reader : in out Util.Serialize.IO.XML.Parser; App : in Application_Access; Context : in EL.Contexts.Default.Default_Context_Access; package Reader_Config is end Reader_Config; -- Read the application configuration file and configure the application procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access); end AWA.Applications.Configs;
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Contexts.Default; with Util.Serialize.IO.XML; -- The <b>AWA.Applications.Configs</b> package reads the application configuration files. package AWA.Applications.Configs is -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. generic Reader : in out Util.Serialize.IO.XML.Parser; App : in Application_Access; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean; package Reader_Config is end Reader_Config; -- Read the application configuration file and configure the application procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean); end AWA.Applications.Configs;
Add an Override_Context parameter for the Reader_Config package to allow or not overriding a <context-param> value
Add an Override_Context parameter for the Reader_Config package to allow or not overriding a <context-param> value
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
fb8f7f1cf7a663a6ff22cbd2255abb8b7de8ebae
awa/regtests/awa_harness.adb
awa/regtests/awa_harness.adb
----------------------------------------------------------------------- -- AWA - Unit tests -- 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 AWA.Testsuite; with Util.Tests; with AWA.Tests; procedure AWA_Harness is procedure Harness is new Util.Tests.Harness (AWA.Testsuite.Suite, AWA.Tests.Initialize); begin Harness ("awa-tests.xml"); end AWA_Harness;
----------------------------------------------------------------------- -- AWA - Unit tests -- 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 AWA.Testsuite; with Util.Tests; with AWA.Tests; procedure AWA_Harness is procedure Harness is new Util.Tests.Harness (AWA.Testsuite.Suite, AWA.Tests.Initialize, AWA.Tests.Finish); begin Harness ("awa-tests.xml"); end AWA_Harness;
Call the Finish procedure after executing the testsuite Finish will destroy the AWA application that was allocated dynamically
Call the Finish procedure after executing the testsuite Finish will destroy the AWA application that was allocated dynamically
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a891d2d63b54fb7100f6845ff8ba9650a6967b7f
regtests/util-serialize-io-json-tests.adb
regtests/util-serialize-io-json-tests.adb
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011, 2016, 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.Stream_IO; with Ada.Characters.Wide_Wide_Latin_1; with Ada.Calendar.Formatting; with Util.Test_Caller; with Util.Log.Loggers; with Util.Streams.Files; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write", Test_Output'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); Check_Parse_Error ("{ ""person"":""\uze""}"); Check_Parse_Error ("{ ""person"":""\u012-""}"); Check_Parse_Error ("{ ""person"":""\u012G""}"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); Check_Parse ("{""person"":""asf"",""age"":""2""}"); Check_Parse ("{ ""person"":""\u0123""}"); Check_Parse ("{ ""person"":""\u4567""}"); Check_Parse ("{ ""person"":""\u89ab""}"); Check_Parse ("{ ""person"":""\ucdef""}"); Check_Parse ("{ ""person"":""\u1CDE""}"); Check_Parse ("{ ""person"":""\u2ABF""}"); Check_Parse ("[{ ""person"":""\u2ABF""}]"); end Test_Parser; -- ------------------------------ -- Generate some output stream for the test. -- ------------------------------ procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is Name : Ada.Strings.Unbounded.Unbounded_String; Wide : constant Wide_Wide_String := Ada.Characters.Wide_Wide_Latin_1.CR & Ada.Characters.Wide_Wide_Latin_1.LF & Ada.Characters.Wide_Wide_Latin_1.HT & Wide_Wide_Character'Val (16#080#) & Wide_Wide_Character'Val (16#1fC#) & Wide_Wide_Character'Val (16#20AC#) & -- Euro sign Wide_Wide_Character'Val (16#2acbf#); T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0); begin Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen"); Stream.Start_Document; Stream.Start_Entity ("root"); Stream.Start_Entity ("person"); Stream.Write_Attribute ("id", 1); Stream.Write_Attribute ("name", Name); Stream.Write_Entity ("name", Name); Stream.Write_Entity ("gender", "female"); Stream.Write_Entity ("volunteer", True); Stream.Write_Entity ("age", 17); Stream.Write_Entity ("date", T); Stream.Write_Wide_Entity ("skin", "olive skin"); Stream.Start_Array ("badges"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "hunter"); Stream.End_Entity ("badge"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "archery"); Stream.End_Entity ("badge"); Stream.End_Array ("badges"); Stream.Start_Entity ("district"); Stream.Write_Attribute ("id", 12); Stream.Write_Wide_Attribute ("industry", "Coal mining"); Stream.Write_Attribute ("state", "<destroyed>"); Stream.Write_Long_Entity ("members", 10_000); Stream.Write_Entity ("description", "<TBW>&"""); Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+="); Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+="); Stream.Write_Wide_Entity ("wide", Wide); Stream.End_Entity ("district"); Stream.End_Entity ("person"); Stream.End_Entity ("root"); Stream.End_Document; end Write_Stream; -- ------------------------------ -- Test the JSON output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Buffer : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.JSON.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000); Stream.Initialize (Output => Buffer'Unchecked_Access); Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "JSON output serialization"); end Test_Output; end Util.Serialize.IO.JSON.Tests;
----------------------------------------------------------------------- -- serialize-io-json-tests -- Unit tests for JSON parser -- Copyright (C) 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Ada.Characters.Wide_Wide_Latin_1; with Ada.Calendar.Formatting; with Util.Test_Caller; with Util.Log.Loggers; with Util.Streams.Files; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.JSON.Tests is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON"); package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)", Test_Parse_Error'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write", Test_Output'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Read", Test_Read'Access); end Add_Tests; -- ------------------------------ -- Check various JSON parsing errors. -- ------------------------------ procedure Test_Parse_Error (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse_Error (Content : in String); procedure Check_Parse_Error (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); Log.Error ("No exception raised for: {0}", Content); exception when Parse_Error => null; end Check_Parse_Error; begin Check_Parse_Error ("{ ""person"":23"); Check_Parse_Error ("{ person: 23]"); Check_Parse_Error ("[ }"); Check_Parse_Error ("{[]}"); Check_Parse_Error ("{"); Check_Parse_Error ("{["); Check_Parse_Error ("{ ""person"); Check_Parse_Error ("{ ""person"":"); Check_Parse_Error ("{ ""person"":""asf"); Check_Parse_Error ("{ ""person"":""asf"""); Check_Parse_Error ("{ ""person"":""asf"","); Check_Parse_Error ("{ ""person"":""\uze""}"); Check_Parse_Error ("{ ""person"":""\u012-""}"); Check_Parse_Error ("{ ""person"":""\u012G""}"); end Test_Parse_Error; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is pragma Unreferenced (T); procedure Check_Parse (Content : in String); procedure Check_Parse (Content : in String) is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse_String (Content, R); exception when Parse_Error => Log.Error ("Parse error for: " & Content); raise; end Check_Parse; begin Check_Parse ("{ ""person"":23}"); Check_Parse ("{ }"); Check_Parse ("{""person"":""asf""}"); Check_Parse ("{""person"":""asf"",""age"":""2""}"); Check_Parse ("{ ""person"":""\u0123""}"); Check_Parse ("{ ""person"":""\u4567""}"); Check_Parse ("{ ""person"":""\u89ab""}"); Check_Parse ("{ ""person"":""\ucdef""}"); Check_Parse ("{ ""person"":""\u1CDE""}"); Check_Parse ("{ ""person"":""\u2ABF""}"); Check_Parse ("[{ ""person"":""\u2ABF""}]"); end Test_Parser; -- ------------------------------ -- Generate some output stream for the test. -- ------------------------------ procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is Name : Ada.Strings.Unbounded.Unbounded_String; Wide : constant Wide_Wide_String := Ada.Characters.Wide_Wide_Latin_1.CR & Ada.Characters.Wide_Wide_Latin_1.LF & Ada.Characters.Wide_Wide_Latin_1.HT & Wide_Wide_Character'Val (16#080#) & Wide_Wide_Character'Val (16#1fC#) & Wide_Wide_Character'Val (16#20AC#) & -- Euro sign Wide_Wide_Character'Val (16#2acbf#); T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0); begin Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen"); Stream.Start_Document; Stream.Start_Entity ("root"); Stream.Start_Entity ("person"); Stream.Write_Attribute ("id", 1); Stream.Write_Attribute ("name", Name); Stream.Write_Entity ("name", Name); Stream.Write_Entity ("gender", "female"); Stream.Write_Entity ("volunteer", True); Stream.Write_Entity ("age", 17); Stream.Write_Entity ("date", T); Stream.Write_Wide_Entity ("skin", "olive skin"); Stream.Start_Array ("badges"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "hunter"); Stream.End_Entity ("badge"); Stream.Start_Entity ("badge"); Stream.Write_Entity ("level", "gold"); Stream.Write_Entity ("name", "archery"); Stream.End_Entity ("badge"); Stream.End_Array ("badges"); Stream.Start_Entity ("district"); Stream.Write_Attribute ("id", 12); Stream.Write_Wide_Attribute ("industry", "Coal mining"); Stream.Write_Attribute ("state", "<destroyed>"); Stream.Write_Long_Entity ("members", 10_000); Stream.Write_Entity ("description", "<TBW>&"""); Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+="); Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+="); Stream.Write_Wide_Entity ("wide", Wide); Stream.End_Entity ("district"); Stream.End_Entity ("person"); Stream.End_Entity ("root"); Stream.End_Document; end Write_Stream; -- ------------------------------ -- Test the JSON output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Buffer : aliased Util.Streams.Texts.Print_Stream; Stream : Util.Serialize.IO.JSON.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000); Stream.Initialize (Output => Buffer'Unchecked_Access); Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "JSON output serialization"); end Test_Output; -- ------------------------------ -- Test reading a JSON content into an Object tree. -- ------------------------------ procedure Test_Read (T : in out Test) is use Util.Beans.Objects; Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass01.json"); Root : Util.Beans.Objects.Object; Value : Util.Beans.Objects.Object; Item : Util.Beans.Objects.Object; begin Root := Read (Path); T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object"); T.Assert (Util.Beans.Objects.Is_Array (Root), "Root object is an array"); Value := Util.Beans.Objects.Get_Value (Root, 1); Util.Tests.Assert_Equals (T, "JSON Test Pattern pass1", Util.Beans.Objects.To_String (Value), "Invalid first element"); Value := Util.Beans.Objects.Get_Value (Root, 4); T.Assert (Util.Beans.Objects.Is_Array (Value), "Element 4 should be an empty array"); Util.Tests.Assert_Equals (T, 0, Util.Beans.Objects.Get_Count (Value), "Invalid array"); Value := Util.Beans.Objects.Get_Value (Root, 8); T.Assert (Util.Beans.Objects.Is_Null (Value), "Element 8 should be null"); Value := Util.Beans.Objects.Get_Value (Root, 9); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Element 9 should not be null"); Item := Util.Beans.Objects.Get_Value (Value, "integer"); Util.Tests.Assert_Equals (T, 1234567890, Util.Beans.Objects.To_Integer (Item), "Invalid integer value"); Item := Util.Beans.Objects.Get_Value (Value, "zero"); Util.Tests.Assert_Equals (T, 0, Util.Beans.Objects.To_Integer (Item), "Invalid integer value (0)"); Item := Util.Beans.Objects.Get_Value (Value, "one"); Util.Tests.Assert_Equals (T, 1, Util.Beans.Objects.To_Integer (Item), "Invalid integer value (1)"); Item := Util.Beans.Objects.Get_Value (Value, "true"); T.Assert (Util.Beans.Objects.Get_Type (Item) = TYPE_BOOLEAN, "The value true should be a boolean"); T.Assert (Util.Beans.Objects.To_Boolean (Item), "The value true should be... true!"); Item := Util.Beans.Objects.Get_Value (Value, "false"); T.Assert (Util.Beans.Objects.Get_Type (Item) = TYPE_BOOLEAN, "The value false should be a boolean"); T.Assert (not Util.Beans.Objects.To_Boolean (Item), "The value false should be... false!"); Item := Util.Beans.Objects.Get_Value (Value, " s p a c e d "); T.Assert (Is_Array (Item), "The value should be an array"); for I in 1 .. 7 loop Util.Tests.Assert_Equals (T, I, To_Integer (Get_Value (Item, I)), "Invalid array value at " & Integer'Image (I)); end loop; end Test_Read; end Util.Serialize.IO.JSON.Tests;
Add a new unit test to verify the Read procedure that parses a JSON file and return an object tree Verify that the object tree contains the expected objects
Add a new unit test to verify the Read procedure that parses a JSON file and return an object tree Verify that the object tree contains the expected objects
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4e93a904f7ee6328c22128681a6d725fcfbb66a0
regtests/wiki-testsuite.adb
regtests/wiki-testsuite.adb
----------------------------------------------------------------------- -- Wiki testsuite - Ada Wiki Test suite -- 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 Wiki.Parsers.Tests; with Wiki.Writers.Tests; with Wiki.Filters.Html.Tests; package body Wiki.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Wiki.Filters.Html.Tests.Add_Tests (Ret); Wiki.Parsers.Tests.Add_Tests (Ret); Wiki.Writers.Tests.Add_Tests (Ret); return Ret; end Suite; end Wiki.Testsuite;
----------------------------------------------------------------------- -- Wiki testsuite - Ada Wiki Test suite -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Parsers.Tests; with Wiki.Tests; with Wiki.Filters.Html.Tests; package body Wiki.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Wiki.Filters.Html.Tests.Add_Tests (Ret); Wiki.Parsers.Tests.Add_Tests (Ret); Wiki.Tests.Add_Tests (Ret); return Ret; end Suite; end Wiki.Testsuite;
Update the testsuite
Update the testsuite
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0de289296b59eb161ef9574f2188e27f1e03fd4d
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- 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 ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with Util.Files; with Util.Strings; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Receive an event from the event channel -- ------------------------------ procedure Receive_Event (Sub : in out Module_Subscriber; Item : in Util.Events.Event'Class) is begin Sub.Module.Receive_Event (ASF.Events.Modules.Module_Event'Class (Item)); end Receive_Event; -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the event subscribers for a given event name. -- ------------------------------ function Get_Subscribers (Plugin : in Module; Event : in String) return String is Subscribers : constant String := Plugin.Get_Config ("event.publish." & Event, ""); begin if Subscribers'Length > 0 then return Subscribers; else return Plugin.Get_Config ("event.publish", ""); end if; end Get_Subscribers; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; To : in String; Content : in ASF.Events.Modules.Module_Event'Class) is Subscribers : constant String := Plugin.Get_Subscribers (To); Target : Module_Access; Last_Pos : Natural := Subscribers'First; Pos : Natural; begin while Last_Pos < Subscribers'Last loop Pos := Util.Strings.Index (Source => Subscribers, Char => ',', From => Last_Pos); if Pos = 0 then Pos := Subscribers'Last + 1; end if; exit when Last_Pos = Pos; Target := Plugin.Find_Module (Subscribers (Last_Pos .. Pos - 1)); if Target = null then Log.Warn ("Event {0} cannot be sent to missing module {1}", To, Subscribers (Last_Pos .. Pos - 1)); return; end if; Target.Channel.Post (Content); Last_Pos := Pos + 1; end loop; end Send_Event; -- ------------------------------ -- Receive an event sent by another module with <b>Send_Event</b> method. -- ------------------------------ procedure Receive_Event (Plugin : in out Module; Content : in ASF.Events.Modules.Module_Event'Class) is begin null; end Receive_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin -- ASF.Beans.Register_Class (Plugin.Factory, Name, Bind); Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Events.Channels.Channel'Class, Name => Util.Events.Channels.Channel_Access); begin Free (Plugin.Channel); end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; To : in String; Content : in ASF.Events.Modules.Module_Event'Class) is begin Manager.Module.Send_Event (To, Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access) is begin Plugin.Self := Plugin'Unchecked_Access; -- ASF.Modules.Module (Plugin).Initialize (App); Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is Paths : constant String := Registry.Config.Get ("app.modules.dir", "./config"); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Subscriber.Module := Plugin; Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration Plugin.Config.Copy (From => Registry.Config, Prefix => Name & ".", Strip => True); -- Configure the event channels for this module declare Kind : constant String := Plugin.Config.Get ("channel.type", "direct"); begin Plugin.Channel := Util.Events.Channels.Create (Name, Kind); Plugin.Channel.Subscribe (Plugin.Subscriber'Access); end; Plugin.Initialize (App); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- 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 ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with Util.Files; with Util.Strings; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Receive an event from the event channel -- ------------------------------ procedure Receive_Event (Sub : in out Module_Subscriber; Item : in Util.Events.Event'Class) is begin Sub.Module.Receive_Event (ASF.Events.Modules.Module_Event'Class (Item)); end Receive_Event; -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the event subscribers for a given event name. -- ------------------------------ function Get_Subscribers (Plugin : in Module; Event : in String) return String is Subscribers : constant String := Plugin.Get_Config ("event.publish." & Event, ""); begin if Subscribers'Length > 0 then return Subscribers; else return Plugin.Get_Config ("event.publish", ""); end if; end Get_Subscribers; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; To : in String; Content : in ASF.Events.Modules.Module_Event'Class) is Subscribers : constant String := Plugin.Get_Subscribers (To); Target : Module_Access; Last_Pos : Natural := Subscribers'First; Pos : Natural; begin while Last_Pos < Subscribers'Last loop Pos := Util.Strings.Index (Source => Subscribers, Char => ',', From => Last_Pos); if Pos = 0 then Pos := Subscribers'Last + 1; end if; exit when Last_Pos = Pos; Target := Plugin.Find_Module (Subscribers (Last_Pos .. Pos - 1)); if Target = null then Log.Warn ("Event {0} cannot be sent to missing module {1}", To, Subscribers (Last_Pos .. Pos - 1)); return; end if; Target.Channel.Post (Content); Last_Pos := Pos + 1; end loop; end Send_Event; -- ------------------------------ -- Receive an event sent by another module with <b>Send_Event</b> method. -- ------------------------------ procedure Receive_Event (Plugin : in out Module; Content : in ASF.Events.Modules.Module_Event'Class) is begin null; end Receive_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is procedure Free is new Ada.Unchecked_Deallocation (Object => Util.Events.Channels.Channel'Class, Name => Util.Events.Channels.Channel_Access); begin Free (Plugin.Channel); end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; To : in String; Content : in ASF.Events.Modules.Module_Event'Class) is begin Manager.Module.Send_Event (To, Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access) is begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is Paths : constant String := Registry.Config.Get ("app.modules.dir", "./config"); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Subscriber.Module := Plugin; Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration Plugin.Config.Copy (From => Registry.Config, Prefix => Name & ".", Strip => True); -- Configure the event channels for this module declare Kind : constant String := Plugin.Config.Get ("channel.type", "direct"); begin Plugin.Channel := Util.Events.Channels.Create (Name, Kind); Plugin.Channel.Subscribe (Plugin.Subscriber'Access); end; Plugin.Initialize (App); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
Update svn:ignore
Update svn:ignore
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
49f1d69d260976fdb45c6be70e25f491a19e6f8b
awa/src/awa-modules.ads
awa/src/awa-modules.ads
----------------------------------------------------------------------- -- awa-modules -- Application Module -- Copyright (C) 2009, 2010, 2011, 2012, 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 Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Log.Loggers; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Serialize.IO; with Util.Listeners; with EL.Expressions; with ASF.Beans; with ASF.Applications; with ADO.Sessions; with AWA.Events; limited with AWA.Applications; -- == AWA Modules == -- A module is a software component that can be integrated in the -- web application. The module can bring a set of service APIs, -- some Ada beans and some presentation files. The AWA framework -- allows to configure various parts of a module when it is integrated -- in an application. Some modules are designed to be re-used by -- several applications (for example a _mail_ module, a _users_ -- module, ...). Other modules could be specific to an application. -- An application will be made of several modules, some will be -- generic some others specific to the application. -- -- === Registration === -- The module should have only one instance per application and it must -- be registered when the application is initialized. The module -- instance should be added to the application record as follows: -- -- type Application is new AWA.Applications.Application with record -- Xxx : aliased Xxx_Module; -- end record; -- -- The application record must override the `Initialize_Module` procedure -- and it must register the module instance. This is done as follows: -- -- overriding -- procedure Initialize_Modules (App : in out Application) is -- begin -- Register (App => App.Self.all'Access, -- Name => Xxx.Module.NAME, -- URI => "xxx", -- Module => App.User_Module'Access); -- end Initialize_Modules; -- -- The module is registered under a unique name. That name is used -- to load the module configuration. -- -- === Configuration === -- The module is configured by using an XML or a properties file. -- The configuration file is used to define: -- -- * the Ada beans that the module defines and uses, -- * the events that the module wants to receive and the action -- that must be performed when the event is posted, -- * the permissions that the module needs and how to check them, -- * the navigation rules which are used for the module web interface, -- * the servlet and filter mappings used by the module -- -- The module configuration is located in the *config* directory -- and must be the name of the module followed by the file extension -- (example: `module-name`.xml or `module-name`.properties). -- -- package AWA.Modules is type Application_Access is access all AWA.Applications.Application'Class; -- ------------------------------ -- Module manager -- ------------------------------ -- -- The <b>Module_Manager</b> represents the root of the logic manager type Module_Manager is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with private; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module_Manager; Name : String; Default : String := "") return String; -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. function Get_Config (Plugin : in Module_Manager; Config : in ASF.Applications.Config_Param) return String; -- ------------------------------ -- Module -- ------------------------------ type Module is abstract new Ada.Finalization.Limited_Controlled with private; type Module_Access is access all Module'Class; -- Get the module name function Get_Name (Plugin : Module) return String; -- Get the base URI for this module function Get_URI (Plugin : Module) return String; -- Get the application in which this module is registered. function Get_Application (Plugin : in Module) return Application_Access; -- Find the module with the given name function Find_Module (Plugin : Module; Name : String) return Module_Access; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : String := "") return String; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : Integer := -1) return Integer; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : Boolean := False) return Boolean; -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the property does not exist, the default configuration value is returned. function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String; -- Get the module configuration property identified by the <tt>Config</tt> parameter. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class); procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config); -- Initialize the configuration file parser represented by <b>Parser</b> to recognize -- the specific configuration recognized by the module. procedure Initialize_Parser (Plugin : in out Module; Parser : in out Util.Serialize.IO.Parser'Class) is null; -- Configures the module after its initialization and after having read its XML configuration. procedure Configure (Plugin : in out Module; Props : in ASF.Applications.Config) is null; -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class); -- Get the database connection for reading function Get_Session (Manager : Module) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session; -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access); -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access); -- Find the module with the given name in the application and add the listener to the -- module listener list. procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access); -- Remove a listener from the module listener list. procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access); -- Finalize the module. overriding procedure Finalize (Plugin : in out Module); type Pool_Module is abstract new Module with private; type Session_Module is abstract new Module with private; generic type Manager_Type is new Module_Manager with private; type Manager_Type_Access is access all Manager_Type'Class; Name : String; function Get_Manager return Manager_Type_Access; -- Get the database connection for reading function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session; -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class); -- ------------------------------ -- Module Registry -- ------------------------------ -- The module registry maintains the list of available modules with -- operations to retrieve them either from a name or from the base URI. type Module_Registry is limited private; type Module_Registry_Access is access all Module_Registry; -- Initialize the registry procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config); -- Register the module in the registry. procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String); -- Find the module with the given name function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access; -- Find the module mapped to a given URI function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access; -- Iterate over the modules that have been registered and execute the <b>Process</b> -- procedure on each of the module instance. procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)); private use Ada.Strings.Unbounded; type Module is abstract new Ada.Finalization.Limited_Controlled with record Registry : Module_Registry_Access; App : Application_Access := null; Name : Unbounded_String; URI : Unbounded_String; Config : ASF.Applications.Config; Self : Module_Access := null; Listeners : Util.Listeners.List; end record; -- Map to find a module from its name or its URI package Module_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Module_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Module_Registry is limited record Config : ASF.Applications.Config; Name_Map : Module_Maps.Map; URI_Map : Module_Maps.Map; end record; type Module_Manager is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with record Module : Module_Access := null; end record; type Pool_Module is new Module with record D : Natural; end record; type Session_Module is new Module with record P : Natural; end record; use Util.Log; -- The logger (used by the generic Get function). Log : constant Loggers.Logger := Loggers.Create ("AWA.Modules"); end AWA.Modules;
----------------------------------------------------------------------- -- awa-modules -- Application Module -- Copyright (C) 2009 - 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Log.Loggers; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Serialize.IO; with Util.Listeners; with EL.Expressions; with ASF.Beans; with ASF.Applications; with ADO.Sessions; with AWA.Events; limited with AWA.Applications; -- == AWA Modules == -- A module is a software component that can be integrated in the -- web application. The module can bring a set of service APIs, -- some Ada beans and some presentation files. The AWA framework -- allows to configure various parts of a module when it is integrated -- in an application. Some modules are designed to be re-used by -- several applications (for example a _mail_ module, a _users_ -- module, ...). Other modules could be specific to an application. -- An application will be made of several modules, some will be -- generic some others specific to the application. -- -- === Registration === -- The module should have only one instance per application and it must -- be registered when the application is initialized. The module -- instance should be added to the application record as follows: -- -- type Application is new AWA.Applications.Application with record -- Xxx : aliased Xxx_Module; -- end record; -- -- The application record must override the `Initialize_Module` procedure -- and it must register the module instance. This is done as follows: -- -- overriding -- procedure Initialize_Modules (App : in out Application) is -- begin -- Register (App => App.Self.all'Access, -- Name => Xxx.Module.NAME, -- URI => "xxx", -- Module => App.User_Module'Access); -- end Initialize_Modules; -- -- The module is registered under a unique name. That name is used -- to load the module configuration. -- -- === Configuration === -- The module is configured by using an XML or a properties file. -- The configuration file is used to define: -- -- * the Ada beans that the module defines and uses, -- * the events that the module wants to receive and the action -- that must be performed when the event is posted, -- * the permissions that the module needs and how to check them, -- * the navigation rules which are used for the module web interface, -- * the servlet and filter mappings used by the module -- -- The module configuration is located in the *config* directory -- and must be the name of the module followed by the file extension -- (example: `module-name`.xml or `module-name`.properties). -- -- package AWA.Modules is type Application_Access is access all AWA.Applications.Application'Class; -- ------------------------------ -- Module manager -- ------------------------------ -- -- The `Module_Manager` represents the root of the logic manager type Module_Manager is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with private; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module_Manager; Name : String; Default : String := "") return String; -- Get the module configuration property identified by the `Config` parameter. -- If the property does not exist, the default configuration value is returned. function Get_Config (Plugin : in Module_Manager; Config : in ASF.Applications.Config_Param) return String; function Get_Config (Plugin : in Module_Manager; Config : in ASF.Applications.Config_Param) return Integer; function Get_Config (Plugin : in Module_Manager; Config : in ASF.Applications.Config_Param) return Boolean; -- ------------------------------ -- Module -- ------------------------------ type Module is abstract new Ada.Finalization.Limited_Controlled with private; type Module_Access is access all Module'Class; -- Get the module name function Get_Name (Plugin : Module) return String; -- Get the base URI for this module function Get_URI (Plugin : Module) return String; -- Get the application in which this module is registered. function Get_Application (Plugin : in Module) return Application_Access; -- Find the module with the given name function Find_Module (Plugin : Module; Name : String) return Module_Access; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : String := "") return String; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : Integer := -1) return Integer; -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : Module; Name : String; Default : Boolean := False) return Boolean; -- Get the module configuration property identified by the `Config` parameter. -- If the property does not exist, the default configuration value is returned. function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return String; function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return Integer; function Get_Config (Plugin : in Module; Config : in ASF.Applications.Config_Param) return Boolean; -- Get the module configuration property identified by the `Config` parameter. -- If the configuration property does not exist, returns the default value. function Get_Config (Plugin : in Module; Name : in String; Default : in String := "") return EL.Expressions.Expression; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class); procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config); -- Initialize the configuration file parser represented by `Parser` to recognize -- the specific configuration recognized by the module. procedure Initialize_Parser (Plugin : in out Module; Parser : in out Util.Serialize.IO.Parser'Class) is null; -- Configures the module after its initialization and after having read its XML configuration. procedure Configure (Plugin : in out Module; Props : in ASF.Applications.Config) is null; -- Send the event to the module. The module identified by `To` is -- found and the event is posted on its event channel. procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class); -- Get the database connection for reading function Get_Session (Manager : Module) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session; -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access); -- Add a listener to the module listner list. The module will invoke the listner -- depending on events or actions that occur in the module. procedure Add_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access); -- Find the module with the given name in the application and add the listener to the -- module listener list. procedure Add_Listener (Plugin : in Module; Name : in String; Item : in Util.Listeners.Listener_Access); -- Remove a listener from the module listener list. procedure Remove_Listener (Into : in out Module; Item : in Util.Listeners.Listener_Access); -- Finalize the module. overriding procedure Finalize (Plugin : in out Module); type Pool_Module is abstract new Module with private; type Session_Module is abstract new Module with private; generic type Manager_Type is new Module_Manager with private; type Manager_Type_Access is access all Manager_Type'Class; Name : String; function Get_Manager return Manager_Type_Access; -- Get the database connection for reading function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session; -- Get the database connection for writing function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session; -- Send the event to the module. The module identified by `To` is -- found and the event is posted on its event channel. procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class); -- ------------------------------ -- Module Registry -- ------------------------------ -- The module registry maintains the list of available modules with -- operations to retrieve them either from a name or from the base URI. type Module_Registry is limited private; type Module_Registry_Access is access all Module_Registry; -- Initialize the registry procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config); -- Register the module in the registry. procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String); -- Find the module with the given name function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access; -- Find the module mapped to a given URI function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access; -- Iterate over the modules that have been registered and execute the `Process` -- procedure on each of the module instance. procedure Iterate (Registry : in Module_Registry; Process : access procedure (Plugin : in out Module'Class)); private use Ada.Strings.Unbounded; type Module is abstract new Ada.Finalization.Limited_Controlled with record Registry : Module_Registry_Access; App : Application_Access := null; Name : Unbounded_String; URI : Unbounded_String; Config : ASF.Applications.Config; Self : Module_Access := null; Listeners : Util.Listeners.List; end record; -- Map to find a module from its name or its URI package Module_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Module_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Module_Registry is limited record Config : ASF.Applications.Config; Name_Map : Module_Maps.Map; URI_Map : Module_Maps.Map; end record; type Module_Manager is new Ada.Finalization.Limited_Controlled and Util.Beans.Basic.Readonly_Bean with record Module : Module_Access := null; end record; type Pool_Module is new Module with record D : Natural; end record; type Session_Module is new Module with record P : Natural; end record; use Util.Log; -- The logger (used by the generic Get function). Log : constant Loggers.Logger := Loggers.Create ("AWA.Modules"); end AWA.Modules;
Add new Get_Config function that return boolean and integer
Add new Get_Config function that return boolean and integer
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
bc6c4229100e4cff0c9b01d6c2b18f1a68ba7e5f
src/asf-navigations.adb
src/asf-navigations.adb
----------------------------------------------------------------------- -- asf-navigations -- Navigations -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Root; with Util.Strings; with Util.Beans.Objects; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ASF.Applications.Main; with ASF.Navigations.Render; package body ASF.Navigations is -- ------------------------------ -- Navigation Case -- ------------------------------ -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations"); -- ------------------------------ -- Check if the navigator specific condition matches the current execution context. -- ------------------------------ function Matches (Navigator : in Navigation_Case; Action : in String; Outcome : in String; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is begin -- outcome must match if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then return False; end if; -- action must match if Navigator.Action /= null and then Navigator.Action.all /= Action then return False; end if; -- condition must be true if not Navigator.Condition.Is_Constant then declare Value : constant Util.Beans.Objects.Object := Navigator.Condition.Get_Value (Context.Get_ELContext.all); begin if not Util.Beans.Objects.To_Boolean (Value) then return False; end if; end; end if; return True; end Matches; -- ------------------------------ -- Navigation Rule -- ------------------------------ -- ------------------------------ -- Search for the navigator that matches the current action, outcome and context. -- Returns the navigator or null if there was no match. -- ------------------------------ function Find_Navigation (Controller : in Rule; Action : in String; Outcome : in String; Context : in Contexts.Faces.Faces_Context'Class) return Navigation_Access is Iter : Navigator_Vector.Cursor := Controller.Navigators.First; Navigator : Navigation_Access; begin while Navigator_Vector.Has_Element (Iter) loop Navigator := Navigator_Vector.Element (Iter); -- Check if this navigator matches the action/outcome. if Navigator.Matches (Action, Outcome, Context) then return Navigator; end if; Navigator_Vector.Next (Iter); end loop; return null; end Find_Navigation; -- ------------------------------ -- Clear the navigation rules. -- ------------------------------ procedure Clear (Controller : in out Rule) is procedure Free is new Ada.Unchecked_Deallocation (Navigation_Case'Class, Navigation_Access); begin while not Controller.Navigators.Is_Empty loop declare Iter : Navigator_Vector.Cursor := Controller.Navigators.Last; Navigator : Navigation_Access := Navigator_Vector.Element (Iter); begin Free (Navigator.Outcome); Free (Navigator.Action); Free (Navigator); Controller.Navigators.Delete (Iter); end; end loop; end Clear; -- ------------------------------ -- Clear the navigation rules. -- ------------------------------ procedure Clear (Controller : in out Navigation_Rules) is procedure Free is new Ada.Unchecked_Deallocation (Rule'Class, Rule_Access); begin while not Controller.Rules.Is_Empty loop declare Iter : Rule_Map.Cursor := Controller.Rules.First; Rule : Rule_Access := Rule_Map.Element (Iter); begin Rule.Clear; Free (Rule); Controller.Rules.Delete (Iter); end; end loop; end Clear; -- ------------------------------ -- Navigation Handler -- ------------------------------ -- ------------------------------ -- Provide a default navigation rules for the view and the outcome when no application -- navigation was found. The default looks for an XHTML file in the same directory as -- the view and which has the base name defined by <b>Outcome</b>. -- ------------------------------ procedure Handle_Default_Navigation (Handler : in Navigation_Handler; View : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Pos : constant Natural := Util.Strings.Rindex (View, '/'); Root : Components.Root.UIViewRoot; View_Handler : access ASF.Applications.Views.View_Handler'Class := Handler.View_Handler; begin if View_Handler = null then View_Handler := Handler.Application.Get_View_Handler; end if; if Pos > 0 then declare Name : constant String := View (View'First .. Pos) & Outcome; begin Log.Debug ("Using default navigation from view {0} to {1}", View, Name); View_Handler.Create_View (Name, Context, Root); end; else Log.Debug ("Using default navigation from view {0} to {1}", View, View); View_Handler.Create_View (Outcome, Context, Root); end if; -- If the 'outcome' refers to a real view, use it. Otherwise keep the current view. if Components.Root.Get_Root (Root) /= null then Context.Set_View_Root (Root); end if; exception when others => Log.Debug ("No suitable navigation rule to navigate from view {0}: {1}", View, Outcome); raise; end Handle_Default_Navigation; -- ------------------------------ -- After executing an action and getting the action outcome, proceed to the navigation -- to the next page. -- ------------------------------ procedure Handle_Navigation (Handler : in Navigation_Handler; Action : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Nav_Rules : constant Navigation_Rules_Access := Handler.Rules; View : constant Components.Root.UIViewRoot := Context.Get_View_Root; Name : constant String := Components.Root.Get_View_Id (View); function Find_Navigation (View : in String) return Navigation_Access; function Find_Navigation (View : in String) return Navigation_Access is Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View)); begin if not Rule_Map.Has_Element (Pos) then return null; end if; return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context); end Find_Navigation; Navigator : Navigation_Access; begin Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome); -- Find an exact match Navigator := Find_Navigation (Name); -- Find a wildcard match if Navigator = null then declare Last : Natural := Name'Last; N : Natural; begin loop N := Util.Strings.Rindex (Name, '/', Last); exit when N = 0; Navigator := Find_Navigation (Name (Name'First .. N) & "*"); exit when Navigator /= null or N = Name'First; Last := N - 1; end loop; end; end if; -- Execute the navigation action. if Navigator /= null then Navigator.Navigate (Context); else Log.Debug ("No navigation rule found for view {0}, action {1} and outcome {2}", Name, Action, Outcome); Navigation_Handler'Class (Handler).Handle_Default_Navigation (Name, Outcome, Context); end if; end Handle_Navigation; -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Handler : in out Navigation_Handler; App : access ASF.Applications.Main.Application'Class) is begin Handler.Rules := new Navigation_Rules; Handler.Application := App; end Initialize; -- ------------------------------ -- Free the storage used by the navigation handler. -- ------------------------------ overriding procedure Finalize (Handler : in out Navigation_Handler) is procedure Free is new Ada.Unchecked_Deallocation (Navigation_Rules, Navigation_Rules_Access); begin if Handler.Rules /= null then Clear (Handler.Rules.all); Free (Handler.Rules); end if; end Finalize; -- ------------------------------ -- Add a navigation case to navigate from the view identifier by <b>From</b> -- to the result view identified by <b>To</b>. Some optional conditions are evaluated -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. -- ------------------------------ procedure Add_Navigation_Case (Handler : in out Navigation_Handler; From : in String; To : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class) is C : constant Navigation_Access := Render.Create_Render_Navigator (To); begin Handler.Add_Navigation_Case (C, From, Outcome, Action, Condition, Context); end Add_Navigation_Case; -- ------------------------------ -- Add a navigation case to navigate from the view identifier by <b>From</b> -- by using the navigation rule defined by <b>Navigator</b>. -- Some optional conditions are evaluated: -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. -- ------------------------------ procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class; Navigator : in Navigation_Access; From : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class) is begin Log.Info ("Add navigation from {0} with outcome {1}", From, Outcome); if Outcome'Length > 0 then Navigator.Outcome := new String '(Outcome); end if; if Action'Length > 0 then Navigator.Action := new String '(Action); end if; if Handler.View_Handler = null then Handler.View_Handler := Handler.Application.Get_View_Handler; end if; if Condition'Length > 0 then Navigator.Condition := EL.Expressions.Create_Expression (Condition, Context); end if; Navigator.View_Handler := Handler.View_Handler; declare View : constant Unbounded_String := To_Unbounded_String (From); Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View); R : Rule_Access; begin if not Rule_Map.Has_Element (Pos) then R := new Rule; Handler.Rules.Rules.Include (Key => View, New_Item => R); else R := Rule_Map.Element (Pos); end if; R.Navigators.Append (Navigator); end; end Add_Navigation_Case; end ASF.Navigations;
----------------------------------------------------------------------- -- asf-navigations -- Navigations -- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Root; with Util.Strings; with Util.Beans.Objects; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ASF.Applications.Main; with ASF.Navigations.Render; package body ASF.Navigations is -- ------------------------------ -- Navigation Case -- ------------------------------ -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations"); -- ------------------------------ -- Check if the navigator specific condition matches the current execution context. -- ------------------------------ function Matches (Navigator : in Navigation_Case; Action : in String; Outcome : in String; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is begin -- outcome must match if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then return False; end if; -- action must match if Navigator.Action /= null and then Navigator.Action.all /= Action then return False; end if; -- condition must be true if not Navigator.Condition.Is_Constant then declare Value : constant Util.Beans.Objects.Object := Navigator.Condition.Get_Value (Context.Get_ELContext.all); begin if not Util.Beans.Objects.To_Boolean (Value) then return False; end if; end; end if; return True; end Matches; -- ------------------------------ -- Navigation Rule -- ------------------------------ -- ------------------------------ -- Search for the navigator that matches the current action, outcome and context. -- Returns the navigator or null if there was no match. -- ------------------------------ function Find_Navigation (Controller : in Rule; Action : in String; Outcome : in String; Context : in Contexts.Faces.Faces_Context'Class) return Navigation_Access is Iter : Navigator_Vector.Cursor := Controller.Navigators.First; Navigator : Navigation_Access; begin while Navigator_Vector.Has_Element (Iter) loop Navigator := Navigator_Vector.Element (Iter); -- Check if this navigator matches the action/outcome. if Navigator.Matches (Action, Outcome, Context) then return Navigator; end if; Navigator_Vector.Next (Iter); end loop; return null; end Find_Navigation; -- ------------------------------ -- Clear the navigation rules. -- ------------------------------ procedure Clear (Controller : in out Rule) is procedure Free is new Ada.Unchecked_Deallocation (Navigation_Case'Class, Navigation_Access); begin while not Controller.Navigators.Is_Empty loop declare Iter : Navigator_Vector.Cursor := Controller.Navigators.Last; Navigator : Navigation_Access := Navigator_Vector.Element (Iter); begin Free (Navigator.Outcome); Free (Navigator.Action); Free (Navigator); Controller.Navigators.Delete (Iter); end; end loop; end Clear; -- ------------------------------ -- Clear the navigation rules. -- ------------------------------ procedure Clear (Controller : in out Navigation_Rules) is procedure Free is new Ada.Unchecked_Deallocation (Rule'Class, Rule_Access); begin while not Controller.Rules.Is_Empty loop declare Iter : Rule_Map.Cursor := Controller.Rules.First; Rule : Rule_Access := Rule_Map.Element (Iter); begin Rule.Clear; Free (Rule); Controller.Rules.Delete (Iter); end; end loop; end Clear; -- ------------------------------ -- Navigation Handler -- ------------------------------ -- ------------------------------ -- Provide a default navigation rules for the view and the outcome when no application -- navigation was found. The default looks for an XHTML file in the same directory as -- the view and which has the base name defined by <b>Outcome</b>. -- ------------------------------ procedure Handle_Default_Navigation (Handler : in Navigation_Handler; View : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Pos : constant Natural := Util.Strings.Rindex (View, '/'); Root : Components.Root.UIViewRoot; View_Handler : access ASF.Applications.Views.View_Handler'Class := Handler.View_Handler; begin if View_Handler = null then View_Handler := Handler.Application.Get_View_Handler; end if; if Pos > 0 then declare Name : constant String := View (View'First .. Pos) & Outcome; begin Log.Debug ("Using default navigation from view {0} to {1}", View, Name); View_Handler.Create_View (Name, Context, Root); end; else Log.Debug ("Using default navigation from view {0} to {1}", View, View); View_Handler.Create_View (Outcome, Context, Root); end if; -- If the 'outcome' refers to a real view, use it. Otherwise keep the current view. if Components.Root.Get_Root (Root) /= null then Context.Set_View_Root (Root); end if; exception when others => Log.Debug ("No suitable navigation rule to navigate from view {0}: {1}", View, Outcome); raise; end Handle_Default_Navigation; -- ------------------------------ -- After executing an action and getting the action outcome, proceed to the navigation -- to the next page. -- ------------------------------ procedure Handle_Navigation (Handler : in Navigation_Handler; Action : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Nav_Rules : constant Navigation_Rules_Access := Handler.Rules; View : constant Components.Root.UIViewRoot := Context.Get_View_Root; Name : constant String := Components.Root.Get_View_Id (View); function Find_Navigation (View : in String) return Navigation_Access; function Find_Navigation (View : in String) return Navigation_Access is Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View)); begin if not Rule_Map.Has_Element (Pos) then return null; end if; return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context); end Find_Navigation; Navigator : Navigation_Access; begin Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome); -- Find an exact match Navigator := Find_Navigation (Name); -- Find a wildcard match if Navigator = null then declare Last : Natural := Name'Last; N : Natural; begin loop N := Util.Strings.Rindex (Name, '/', Last); exit when N = 0; Navigator := Find_Navigation (Name (Name'First .. N) & "*"); exit when Navigator /= null or N = Name'First; Last := N - 1; end loop; end; end if; -- Execute the navigation action. if Navigator /= null then Navigator.Navigate (Context); else Log.Debug ("No navigation rule found for view {0}, action {1} and outcome {2}", Name, Action, Outcome); Navigation_Handler'Class (Handler).Handle_Default_Navigation (Name, Outcome, Context); end if; end Handle_Navigation; -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Handler : in out Navigation_Handler; App : access ASF.Applications.Main.Application'Class) is begin Handler.Rules := new Navigation_Rules; Handler.Application := App; end Initialize; -- ------------------------------ -- Free the storage used by the navigation handler. -- ------------------------------ overriding procedure Finalize (Handler : in out Navigation_Handler) is procedure Free is new Ada.Unchecked_Deallocation (Navigation_Rules, Navigation_Rules_Access); begin if Handler.Rules /= null then Clear (Handler.Rules.all); Free (Handler.Rules); end if; end Finalize; -- ------------------------------ -- Add a navigation case to navigate from the view identifier by <b>From</b> -- to the result view identified by <b>To</b>. Some optional conditions are evaluated -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. -- ------------------------------ procedure Add_Navigation_Case (Handler : in out Navigation_Handler; From : in String; To : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class) is C : constant Navigation_Access := Render.Create_Render_Navigator (To, 0); begin Handler.Add_Navigation_Case (C, From, Outcome, Action, Condition, Context); end Add_Navigation_Case; -- ------------------------------ -- Add a navigation case to navigate from the view identifier by <b>From</b> -- by using the navigation rule defined by <b>Navigator</b>. -- Some optional conditions are evaluated: -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. -- ------------------------------ procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class; Navigator : in Navigation_Access; From : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class) is begin Log.Info ("Add navigation from {0} with outcome {1}", From, Outcome); if Outcome'Length > 0 then Navigator.Outcome := new String '(Outcome); end if; if Action'Length > 0 then Navigator.Action := new String '(Action); end if; if Handler.View_Handler = null then Handler.View_Handler := Handler.Application.Get_View_Handler; end if; if Condition'Length > 0 then Navigator.Condition := EL.Expressions.Create_Expression (Condition, Context); end if; Navigator.View_Handler := Handler.View_Handler; declare View : constant Unbounded_String := To_Unbounded_String (From); Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View); R : Rule_Access; begin if not Rule_Map.Has_Element (Pos) then R := new Rule; Handler.Rules.Rules.Include (Key => View, New_Item => R); else R := Rule_Map.Element (Pos); end if; R.Navigators.Append (Navigator); end; end Add_Navigation_Case; end ASF.Navigations;
Update call to Create_Render_Navigator
Update call to Create_Render_Navigator
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
e06d6262633141f64fc025fa5b73ecc7833306d7
src/orka/implementation/orka-jobs-executors.adb
src/orka/implementation/orka-jobs-executors.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.Real_Time; with Ada.Tags; with Ada.Text_IO; with Orka.Containers.Bounded_Vectors; with Orka.Futures; package body Orka.Jobs.Executors is function Get_Root_Dependent (Element : Job_Ptr) return Job_Ptr is Result : Job_Ptr := Element; begin while Result.Dependent /= Null_Job loop Result := Result.Dependent; end loop; return Result; end Get_Root_Dependent; procedure Execute_Jobs (Name : String; Kind : Queues.Executor_Kind; Queue : Queues.Queue_Ptr) is use type Ada.Real_Time.Time; use type Futures.Status; Pair : Queues.Pair; Stop : Boolean := False; Null_Pair : constant Queues.Pair := Queues.Get_Null_Pair; package Vectors is new Orka.Containers.Bounded_Vectors (Job_Ptr, Get_Null_Job); T0, T1, T2 : Ada.Real_Time.Time; begin loop T0 := Ada.Real_Time.Clock; Queue.Dequeue (Kind) (Pair, Stop); exit when Stop; declare Job : Job_Ptr renames Pair.Job; Future : Futures.Pointers.Reference renames Pair.Future.Get; Promise : Futures.Promise'Class renames Futures.Promise'Class (Future.Value.all); Jobs : Vectors.Vector (Capacity => Maximum_Enqueued_By_Job); procedure Enqueue (Element : Job_Ptr) is begin Jobs.Append (Element); end Enqueue; procedure Set_Root_Dependent (Last_Job : Job_Ptr) is Root_Dependents : Vectors.Vector (Capacity => Jobs.Length); procedure Set_Dependencies (Elements : Vectors.Element_Array) is begin Last_Job.Set_Dependencies (Dependency_Array (Elements)); end Set_Dependencies; begin for Job of Jobs loop declare Root : constant Job_Ptr := Get_Root_Dependent (Job); begin if not (for some Dependent of Root_Dependents => Root = Dependent) then Root_Dependents.Append (Root); end if; end; end loop; Root_Dependents.Query (Set_Dependencies'Access); end Set_Root_Dependent; begin T1 := Ada.Real_Time.Clock; if Future.Current_Status = Futures.Waiting then Promise.Set_Status (Futures.Running); end if; begin Job.Execute (Enqueue'Access); exception when Error : others => Promise.Set_Failed (Error); raise; end; T2 := Ada.Real_Time.Clock; declare Waiting_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T1 - T0); Running_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T2 - T1); Tag : String renames Ada.Tags.Expanded_Name (Job'Tag); begin Ada.Text_IO.Put_Line (Name & " (blocked" & Waiting_Time'Image & " ms) executed job " & Tag & " in" & Running_Time'Image & " ms"); end; if Job.Dependent /= Null_Job then -- Make the root dependents of the jobs in Jobs -- dependencies of Job.Dependent if not Jobs.Empty then Set_Root_Dependent (Job.Dependent); end if; -- If another job depends on this job, decrement its dependencies counter -- and if it has reached zero then it can be scheduled if Job.Dependent.Decrement_Dependencies then Queue.Enqueue (Job.Dependent, Pair.Future); end if; elsif Jobs.Empty then Promise.Set_Status (Futures.Done); else -- If the job has enqueued new jobs, we need to create an -- empty job which has the root dependents of these new jobs -- as dependencies. This is so that the empty job will be the -- last job that is given Pair.Future Set_Root_Dependent (Create_Empty_Job); end if; if not Jobs.Empty then for Job of Jobs loop Queue.Enqueue (Job, Pair.Future); end loop; end if; Free (Job); end; -- Finalize the smart pointer (Pair.Future) to reduce the number -- of references to the Future object Pair := Null_Pair; end loop; end Execute_Jobs; end Orka.Jobs.Executors;
-- 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.Real_Time; -- with Ada.Tags; -- with Ada.Text_IO; with Orka.Containers.Bounded_Vectors; with Orka.Futures; package body Orka.Jobs.Executors is function Get_Root_Dependent (Element : Job_Ptr) return Job_Ptr is Result : Job_Ptr := Element; begin while Result.Dependent /= Null_Job loop Result := Result.Dependent; end loop; return Result; end Get_Root_Dependent; procedure Execute_Jobs (Name : String; Kind : Queues.Executor_Kind; Queue : Queues.Queue_Ptr) is use type Ada.Real_Time.Time; use type Futures.Status; Pair : Queues.Pair; Stop : Boolean := False; Null_Pair : constant Queues.Pair := Queues.Get_Null_Pair; package Vectors is new Orka.Containers.Bounded_Vectors (Job_Ptr, Get_Null_Job); -- T0, T1, T2 : Ada.Real_Time.Time; begin loop -- T0 := Ada.Real_Time.Clock; Queue.Dequeue (Kind) (Pair, Stop); exit when Stop; declare Job : Job_Ptr renames Pair.Job; Future : Futures.Pointers.Reference renames Pair.Future.Get; Promise : Futures.Promise'Class renames Futures.Promise'Class (Future.Value.all); Jobs : Vectors.Vector (Capacity => Maximum_Enqueued_By_Job); procedure Enqueue (Element : Job_Ptr) is begin Jobs.Append (Element); end Enqueue; procedure Set_Root_Dependent (Last_Job : Job_Ptr) is Root_Dependents : Vectors.Vector (Capacity => Jobs.Length); procedure Set_Dependencies (Elements : Vectors.Element_Array) is begin Last_Job.Set_Dependencies (Dependency_Array (Elements)); end Set_Dependencies; begin for Job of Jobs loop declare Root : constant Job_Ptr := Get_Root_Dependent (Job); begin if not (for some Dependent of Root_Dependents => Root = Dependent) then Root_Dependents.Append (Root); end if; end; end loop; Root_Dependents.Query (Set_Dependencies'Access); end Set_Root_Dependent; -- Tag : String renames Ada.Tags.Expanded_Name (Job'Tag); begin -- T1 := Ada.Real_Time.Clock; -- Ada.Text_IO.Put_Line (Name & " executing job " & Tag); if Future.Current_Status = Futures.Waiting then Promise.Set_Status (Futures.Running); end if; begin Job.Execute (Enqueue'Access); exception when Error : others => Promise.Set_Failed (Error); raise; end; -- T2 := Ada.Real_Time.Clock; -- declare -- Waiting_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T1 - T0); -- Running_Time : constant Duration := 1e3 * Ada.Real_Time.To_Duration (T2 - T1); -- begin -- Ada.Text_IO.Put_Line (Name & " (blocked" & Waiting_Time'Image & " ms) executed job " & Tag & " in" & Running_Time'Image & " ms"); -- end; if Job.Dependent /= Null_Job then -- Make the root dependents of the jobs in Jobs -- dependencies of Job.Dependent if not Jobs.Empty then Set_Root_Dependent (Job.Dependent); end if; -- If another job depends on this job, decrement its dependencies counter -- and if it has reached zero then it can be scheduled if Job.Dependent.Decrement_Dependencies then Queue.Enqueue (Job.Dependent, Pair.Future); end if; elsif Jobs.Empty then Promise.Set_Status (Futures.Done); -- Ada.Text_IO.Put_Line (Name & " completed graph with job " & Tag); else -- If the job has enqueued new jobs, we need to create an -- empty job which has the root dependents of these new jobs -- as dependencies. This is so that the empty job will be the -- last job that is given Pair.Future Set_Root_Dependent (Create_Empty_Job); end if; if not Jobs.Empty then for Job of Jobs loop Queue.Enqueue (Job, Pair.Future); end loop; end if; Free (Job); end; -- Finalize the smart pointer (Pair.Future) to reduce the number -- of references to the Future object Pair := Null_Pair; end loop; end Execute_Jobs; end Orka.Jobs.Executors;
Comment debugging prints in package Orka.Jobs.Executors
orka: Comment debugging prints in package Orka.Jobs.Executors These prints are generated each frame for every job, so they generate a lot of text. Keep it commented in the code though because it's still useful for debugging. Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
b65502b00c7bc9eb0f6d4a68e24627334bdae789
src/el-objects-hash.adb
src/el-objects-hash.adb
----------------------------------------------------------------------- -- EL.Objects.Hash -- Hash on an object -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Characters.Conversions; with Ada.Unchecked_Conversion; with Interfaces; with EL.Beans; function EL.Objects.Hash (Key : in Object) return Ada.Containers.Hash_Type is use Ada.Containers; use Ada.Strings; use Ada.Characters.Conversions; use Interfaces; use EL.Beans; type Unsigned_32_Array is array (Natural range <>) of Unsigned_32; subtype U32_For_Float is Unsigned_32_Array (1 .. Long_Long_Float'Size / 32); subtype U32_For_Long is Unsigned_32_Array (1 .. Long_Long_Integer'Size / 32); subtype U32_For_Access is Unsigned_32_Array (1 .. Readonly_Bean_Access'Size / 32); -- Hash the integer and floats using 32-bit values. function To_U32_For_Long is new Ada.Unchecked_Conversion (Source => Long_Long_Integer, Target => U32_For_Long); -- Likewise for floats. function To_U32_For_Float is new Ada.Unchecked_Conversion (Source => Long_Long_Float, Target => U32_For_Float); -- Likewise for the bean pointer function To_U32_For_Access is new Ada.Unchecked_Conversion (Source => Readonly_Bean_Access, Target => U32_For_Access); Value : Unsigned_64 := 0; begin case key.V.Of_Type is when TYPE_NULL => return 0; when TYPE_BOOLEAN => if Key.V.Bool_Value then return 1; else return 2; end if; when TYPE_INTEGER => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Int_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_FLOAT => declare U32 : constant U32_For_Float := To_U32_For_Float (Key.V.Float_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_STRING => if Key.V.Proxy = null then return 0; else return Hash (Key.V.Proxy.String_Value.all); end if; when TYPE_TIME => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Time_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_WIDE_STRING => if Key.V.Proxy = null then return 0; else return Hash (To_String (Key.V.Proxy.Wide_String_Value.all)); end if; when TYPE_BEAN => if Key.V.Proxy.Bean = null then return 0; end if; declare U32 : constant U32_For_Access := To_U32_For_Access (Key.V.Proxy.Bean.all'Access); Val : Unsigned_32 := U32 (U32'First); -- The loop is not executed if pointers are 32-bit wide. pragma Warnings (Off); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; end case; -- Hash the 64-bit value into a 32-bit result that fits in Hash_Type. Value := (Value and 16#0ffffffff#) xor (Shift_Right (Value, 32)); return Hash_Type (Value); end EL.Objects.Hash;
----------------------------------------------------------------------- -- EL.Objects.Hash -- Hash on an object -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Characters.Conversions; with Ada.Unchecked_Conversion; with Interfaces; with EL.Beans; function EL.Objects.Hash (Key : in Object) return Ada.Containers.Hash_Type is use Ada.Containers; use Ada.Strings; use Ada.Characters.Conversions; use Interfaces; use EL.Beans; type Unsigned_32_Array is array (Natural range <>) of Unsigned_32; subtype U32_For_Float is Unsigned_32_Array (1 .. Long_Long_Float'Size / 32); subtype U32_For_Long is Unsigned_32_Array (1 .. Long_Long_Integer'Size / 32); subtype U32_For_Access is Unsigned_32_Array (1 .. Readonly_Bean_Access'Size / 32); -- Hash the integer and floats using 32-bit values. function To_U32_For_Long is new Ada.Unchecked_Conversion (Source => Long_Long_Integer, Target => U32_For_Long); -- Likewise for floats. function To_U32_For_Float is new Ada.Unchecked_Conversion (Source => Long_Long_Float, Target => U32_For_Float); -- Likewise for the bean pointer function To_U32_For_Access is new Ada.Unchecked_Conversion (Source => Readonly_Bean_Access, Target => U32_For_Access); begin case key.V.Of_Type is when TYPE_NULL => return 0; when TYPE_BOOLEAN => if Key.V.Bool_Value then return 1; else return 2; end if; when TYPE_INTEGER => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Int_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_FLOAT => declare U32 : constant U32_For_Float := To_U32_For_Float (Key.V.Float_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_STRING => if Key.V.Proxy = null then return 0; else return Hash (Key.V.Proxy.String_Value.all); end if; when TYPE_TIME => declare U32 : constant U32_For_Long := To_U32_For_Long (Key.V.Time_Value); Val : Unsigned_32 := U32 (U32'First); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; when TYPE_WIDE_STRING => if Key.V.Proxy = null then return 0; else return Hash (To_String (Key.V.Proxy.Wide_String_Value.all)); end if; when TYPE_BEAN => if Key.V.Proxy.Bean = null then return 0; end if; declare U32 : constant U32_For_Access := To_U32_For_Access (Key.V.Proxy.Bean.all'Access); Val : Unsigned_32 := U32 (U32'First); -- The loop is not executed if pointers are 32-bit wide. pragma Warnings (Off); begin for I in U32'First + 1 .. U32'Last loop Val := Val xor U32 (I); end loop; return Hash_Type (Val); end; end case; end EL.Objects.Hash;
Remove unreachable code
Remove unreachable code
Ada
apache-2.0
stcarrez/ada-el
1a8bbc0848f441de664f4e7abf40beb5d38e1195
awa/src/awa-permissions-services.ads
awa/src/awa-permissions-services.ads
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with Util.Beans.Objects; with EL.Functions; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Policies; with Security.Contexts; package AWA.Permissions.Services is -- Register the security EL functions in the EL mapper. procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); type Permission_Manager is new Security.Policies.Policy_Manager with private; type Permission_Manager_Access is access all Permission_Manager'Class; -- Get the permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access; -- Get the application instance. function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access; -- Set the application instance. procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access); -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b> in the <b>Workspace</b>. procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type); -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Create a permission manager for the given application. function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access; -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; private type Permission_Manager is new Security.Policies.Policy_Manager with record App : AWA.Applications.Application_Access := null; end record; end AWA.Permissions.Services;
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Applications; with Util.Beans.Objects; with EL.Functions; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Policies; with Security.Contexts; package AWA.Permissions.Services is -- Register the security EL functions in the EL mapper. procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); type Permission_Manager is new Security.Policies.Policy_Manager with private; type Permission_Manager_Access is access all Permission_Manager'Class; -- Get the permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access; -- Get the application instance. function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access; -- Set the application instance. procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access); -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b> in the <b>Workspace</b>. procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type); -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ); -- Create a permission manager for the given application. function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access; -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; -- Delete all the permissions for a user and on the given workspace. procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Workspace : in ADO.Identifier); private type Permission_Manager is new Security.Policies.Policy_Manager with record App : AWA.Applications.Application_Access := null; end record; end AWA.Permissions.Services;
Declare the Delete_Permissions procedure
Declare the Delete_Permissions procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b8fd2928c4d15c39fa668370aee452bc6a52e1ea
regtests/dlls/util-systems-dlls-tests.ads
regtests/dlls/util-systems-dlls-tests.ads
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- 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.Tests; package Util.Systems.Dlls.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the loading a shared library. procedure Test_Load (T : in out Test); -- Test getting a shared library symbol. procedure Test_Get_Symbol (T : in out Test); end Util.Systems.Dlls.Tests;
----------------------------------------------------------------------- -- util-systems-dlls-tests -- Unit tests for shared libraries -- 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.Tests; package Util.Systems.DLLs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the loading a shared library. procedure Test_Load (T : in out Test); -- Test getting a shared library symbol. procedure Test_Get_Symbol (T : in out Test); end Util.Systems.DLLs.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
609683647178322f180b3b5cf9ad814780b30670
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 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.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; begin Log.Info ("Set connection URI: {0}", URI); 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 while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; 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; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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; begin Log.Info ("Set connection URI: {0}", URI); 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 while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; 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; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; 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;
Implement the Get_Driver function
Implement the Get_Driver function
Ada
apache-2.0
stcarrez/ada-ado
045deda4d7a812187190692aa0426b466cd34e03
src/sys/streams/util-streams-buffered.ads
src/sys/streams/util-streams-buffered.ads
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; -- == Buffered Streams == -- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output -- and input stream respectively which manages an output or input buffer. The data is -- first written to the buffer and when the buffer is full or flushed, it gets written -- to the target output stream. -- -- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. For example, a -- pipe stream could be created and configured to use the buffer as follows: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Output_Buffer_Stream; -- ... -- Buffer.Initialize (Output => Pipe'Access, -- Size => 1024); -- -- In this example, the buffer of 1024 bytes is configured to flush its content to the -- pipe input stream so that what is written to the buffer will be received as input by -- the program. -- The `Output_Buffer_Stream` provides write operation that deal only with binary data -- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from -- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides -- several operations to write character and strings. -- -- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size -- and either an input stream or an input content. When configured, the input stream is used -- to fill the input stream buffer. The buffer configuration is very similar as the -- output stream: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Access, Size => 1024); -- -- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus -- getting the program's output. package Util.Streams.Buffered is pragma Preelaborate; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- ----------------------- -- Output buffer stream -- ----------------------- -- The <b>Output_Buffer_Stream</b> is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call <b>Flush</b> to make sure the data -- is written to the target stream. The <b>Flush</b> operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream with private; -- Initialize the stream to write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Output_Buffer_Stream); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Output_Buffer_Stream); -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Flush the buffer stream to the unbounded string. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String); -- Flush the stream and release the buffer. overriding procedure Finalize (Stream : in out Output_Buffer_Stream); -- Get the number of element in the stream. function Get_Size (Stream : in Output_Buffer_Stream) return Natural; type Input_Buffer_Stream is limited new Input_Stream with private; -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String); -- Initialize the stream to read the given streams. procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive); -- Initialize the stream from the buffer created for an output stream. procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Output_Buffer_Stream'Class); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Input_Buffer_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; private use Ada.Streams; type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The output stream to use for flushing the buffer. Output : access Output_Stream'Class; No_Flush : Boolean := False; end record; type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Input_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The input stream to use to fill the buffer. Input : access Input_Stream'Class; -- Reached end of file when reading. Eof : Boolean := False; end record; -- Release the buffer. overriding procedure Finalize (Object : in out Input_Buffer_Stream); end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; -- == Buffered Streams == -- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output -- and input stream respectively which manages an output or input buffer. The data is -- first written to the buffer and when the buffer is full or flushed, it gets written -- to the target output stream. -- -- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well -- as the target output stream onto which the data will be flushed. For example, a -- pipe stream could be created and configured to use the buffer as follows: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Output_Buffer_Stream; -- ... -- Buffer.Initialize (Output => Pipe'Access, -- Size => 1024); -- -- In this example, the buffer of 1024 bytes is configured to flush its content to the -- pipe input stream so that what is written to the buffer will be received as input by -- the program. -- The `Output_Buffer_Stream` provides write operation that deal only with binary data -- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from -- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides -- several operations to write character and strings. -- -- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size -- and either an input stream or an input content. When configured, the input stream is used -- to fill the input stream buffer. The buffer configuration is very similar as the -- output stream: -- -- with Util.Streams.Buffered; -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Access, Size => 1024); -- -- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus -- getting the program's output. package Util.Streams.Buffered is pragma Preelaborate; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- ----------------------- -- Output buffer stream -- ----------------------- -- The <b>Output_Buffer_Stream</b> is an output stream which uses -- an intermediate buffer to write the data. -- -- It is necessary to call <b>Flush</b> to make sure the data -- is written to the target stream. The <b>Flush</b> operation will -- be called when finalizing the output buffer stream. type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream with private; -- Initialize the stream to write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Output_Buffer_Stream); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Output_Buffer_Stream); -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Flush the buffer stream to the unbounded string. procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String); -- Flush the stream and release the buffer. overriding procedure Finalize (Stream : in out Output_Buffer_Stream); -- Get the number of element in the stream. function Get_Size (Stream : in Output_Buffer_Stream) return Natural; type Input_Buffer_Stream is limited new Input_Stream with private; -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String); -- Initialize the stream to read the given streams. procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive); -- Initialize the stream from the buffer created for an output stream. procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Output_Buffer_Stream'Class); -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Input_Buffer_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character); procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element); procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_Character); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean; private use Ada.Streams; type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The output stream to use for flushing the buffer. Output : access Output_Stream'Class; No_Flush : Boolean := False; end record; type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled and Input_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The input stream to use to fill the buffer. Input : access Input_Stream'Class; -- Reached end of file when reading. Eof : Boolean := False; end record; -- Release the buffer. overriding procedure Finalize (Object : in out Input_Buffer_Stream); end Util.Streams.Buffered;
Declare new Read procedures to read UTF-8 sequences in Wide_Wide character and string
Declare new Read procedures to read UTF-8 sequences in Wide_Wide character and string
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ca6b45d381d856c11c27ac6f2274950556dd3fb4
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural); -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Render_List_Item (Engine : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Document : in out Html_Renderer); private procedure Close_Paragraph (Document : in out Html_Renderer); procedure Open_Paragraph (Document : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type); end Wiki.Render.Html;
Rename Add_List_Item into Render_List_Item
Rename Add_List_Item into Render_List_Item
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
12d0a5f0857fd43d269390cd2d3571baf5274847
regtests/asf-applications-views-tests.adb
regtests/asf-applications-views-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for ASF.Applications.Views -- 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.Text_IO; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Ada.Directories; with Util.Test_Caller; with Util.Files; with Util.Measures; package body ASF.Applications.Views.Tests is use Ada.Strings.Unbounded; overriding procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- Set up performed before each test case -- Test loading of facelet file procedure Test_Load_Facelet (T : in out Test) is use ASF; use ASF.Contexts.Faces; App : Applications.Main.Application; -- H : Applications.Views.View_Handler; View_Name : constant String := To_String (T.File); Result_File : constant String := To_String (T.Result); Conf : Applications.Config; App_Factory : Applications.Main.Application_Factory; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); App.Initialize (Conf, App_Factory); App.Set_Global ("function", "Test_Load_Facelet"); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Rep : ASF.Responses.Mockup.Response; Content : Unbounded_String; begin Req.Set_Method ("GET"); Req.Set_Path_Info (View_Name); Req.Set_Parameter ("file-name", To_String (T.Name)); Req.Set_Header ("file", To_String (T.Name)); App.Dispatch (Page => View_Name, Request => Req, Response => Rep); Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view " & View_Name); Rep.Read_Content (Content); Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Restore and render view"); end; end loop; end Test_Load_Facelet; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String is begin return Util.Tests.Format ("Test " & To_String (T.Name)); end Name; -- Perform the test. overriding procedure Run_Test (T : in out Test) is begin T.Test_Load_Facelet; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; Result_Dir : constant String := "regtests/result/views"; Dir : constant String := "regtests/files/views"; Expect_Dir : constant String := "regtests/expect/views"; Path : constant String := Util.Tests.Get_Path (Dir); Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; begin if Kind (Path) = Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" then Tst := new Test; Tst.Name := To_Unbounded_String (Dir & "/" & Simple); Tst.File := To_Unbounded_String ("views/" & Simple); Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple); Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple); Suite.Add_Test (Tst); end if; end; end loop; end Add_Tests; end ASF.Applications.Views.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for ASF.Applications.Views -- 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.Text_IO; with ASF.Applications.Main; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Ada.Directories; with Util.Test_Caller; with Util.Files; with Util.Measures; package body ASF.Applications.Views.Tests is use Ada.Strings.Unbounded; overriding procedure Set_Up (T : in out Test) is begin null; end Set_Up; -- Set up performed before each test case -- Test loading of facelet file procedure Test_Load_Facelet (T : in out Test) is use ASF; use ASF.Contexts.Faces; App : Applications.Main.Application; -- H : Applications.Views.View_Handler; View_Name : constant String := To_String (T.File); Result_File : constant String := To_String (T.Result); Conf : Applications.Config; App_Factory : Applications.Main.Application_Factory; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); App.Initialize (Conf, App_Factory); App.Set_Global ("function", "Test_Load_Facelet"); for I in 1 .. 2 loop declare S : Util.Measures.Stamp; Req : ASF.Requests.Mockup.Request; Rep : ASF.Responses.Mockup.Response; Content : Unbounded_String; begin Req.Set_Method ("GET"); Req.Set_Path_Info (View_Name); Req.Set_Parameter ("file-name", To_String (T.Name)); Req.Set_Header ("file", To_String (T.Name)); App.Dispatch (Page => View_Name, Request => Req, Response => Rep); Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view " & View_Name); Rep.Read_Content (Content); Util.Files.Write_File (Result_File, Content); Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Restore and render view"); end; end loop; end Test_Load_Facelet; -- Test case name overriding function Name (T : Test) return Util.Tests.Message_String is begin return Util.Tests.Format ("Test " & To_String (T.Name)); end Name; -- Perform the test. overriding procedure Run_Test (T : in out Test) is begin T.Test_Load_Facelet; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; Result_Dir : constant String := "regtests/result/views"; Dir : constant String := "regtests/files/views"; Expect_Dir : constant String := "regtests/expect/views"; Path : constant String := Util.Tests.Get_Path (Dir); Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir); Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir); Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; begin if Kind (Path) = Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" then Tst := new Test; Tst.Name := To_Unbounded_String (Dir & "/" & Simple); Tst.File := To_Unbounded_String ("views/" & Simple); Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple); Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Tests; end ASF.Applications.Views.Tests;
Fix compilation when Ahven is used as a test framework
Fix compilation when Ahven is used as a test framework
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
34a1a468e5b375ac3c387c9e2595a7c1f1aadbb4
regtests/asf-servlets-tests.adb
regtests/asf-servlets-tests.adb
----------------------------------------------------------------------- -- Sessions Tests - Unit tests for ASF.Sessions -- 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.Test_Caller; with Util.Measures; with ASF.Applications; with ASF.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; package body ASF.Servlets.Tests is use Util.Tests; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write ("URI: " & Request.Get_Request_URI); Response.Set_Status (Responses.SC_OK); end Do_Get; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is begin null; end Do_Post; S1 : aliased Test_Servlet1; S2 : aliased Test_Servlet2; -- ------------------------------ -- Test request dispatcher and servlet invocation -- ------------------------------ procedure Test_Request_Dispatcher (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); declare Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => "/home/test.jsf"); Req : ASF.Requests.Mockup.Request; Resp : ASF.Responses.Mockup.Response; Result : Unbounded_String; begin T.Assert (Dispatcher.Mapping /= null, "No mapping found"); Req.Set_Request_URI ("test1"); Req.Set_Method ("GET"); Forward (Dispatcher, Req, Resp); -- Check the response after the Test_Servlet1.Do_Get method execution. Resp.Read_Content (Result); Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status"); Assert_Equals (T, "URI: test1", Result, "Invalid content"); Req.Set_Method ("POST"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status, "Invalid status for an operation not implemented"); end; end Test_Request_Dispatcher; -- ------------------------------ -- Test add servlet -- ------------------------------ procedure Test_Add_Servlet (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet"); begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); T.Assert (False, "No exception raised if the servlet is registered several times"); exception when Servlet_Error => null; end; end Test_Add_Servlet; -- ------------------------------ -- Test getting a resource path -- ------------------------------ procedure Test_Get_Resource (T : in out Test) is Ctx : Servlet_Registry; Conf : Applications.Config; S1 : aliased Test_Servlet1; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); Ctx.Set_Init_Parameters (Conf); Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); -- Resource exist, check the returned path. declare P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml"); begin Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml", P, "Invalid resource path"); end; -- Resource does not exist declare P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml"); begin Assert_Equals (T, "", P, "Invalid resource path for missing resource"); end; end Test_Get_Resource; -- ------------------------------ -- Check that the mapping for the given URI matches the server. -- ------------------------------ procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access) is Map : constant Mapping_Access := Ctx.Find_Mapping (URI); begin if Map = null then T.Assert (Server = null, "No mapping returned for URI: " & URI); else T.Assert (Server /= null, "A mapping is returned for URI: " & URI); T.Assert (Map.Servlet = Server, "Invalid mapping returned for URI: " & URI); end if; end Check_Mapping; -- ------------------------------ -- Test session creation. -- ------------------------------ procedure Test_Create_Servlet (T : in out Test) is Ctx : Servlet_Registry; Map : Mapping_Access; begin Ctx.Add_Servlet (Name => "Faces", Server => S1'Access); Ctx.Add_Servlet (Name => "Text", Server => S2'Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text"); -- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access); Ctx.Mappings.Dump_Map (" "); T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access); T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access); T.Check_Mapping (Ctx, "/server/info", S1'Access); T.Check_Mapping (Ctx, "/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf"); end loop; Util.Measures.Report (St, "Find 1000 mapping (extension)"); end; T.Assert (Map /= null, "No mapping for 'joe.jsf'"); T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); T.Assert (Map.Servlet = S1'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2"); end loop; Util.Measures.Report (St, "Find 1000 mapping (path)"); end; T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'"); T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); T.Assert (Map.Servlet = S2'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); end Test_Create_Servlet; package Caller is new Util.Test_Caller (Test, "Servlets"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping", Test_Create_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet", Test_Add_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher", Test_Request_Dispatcher'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource", Test_Get_Resource'Access); end Add_Tests; end ASF.Servlets.Tests;
----------------------------------------------------------------------- -- Sessions Tests - Unit tests for ASF.Sessions -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Measures; with ASF.Applications; with ASF.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; package body ASF.Servlets.Tests is use Util.Tests; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write ("URI: " & Request.Get_Request_URI); Response.Set_Status (Responses.SC_OK); end Do_Get; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is begin null; end Do_Post; S1 : aliased Test_Servlet1; S2 : aliased Test_Servlet2; -- ------------------------------ -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. -- ------------------------------ procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String) is Dispatcher : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (Path => URI); Req : ASF.Requests.Mockup.Request; Resp : ASF.Responses.Mockup.Response; Result : Unbounded_String; begin T.Assert (Dispatcher.Mapping /= null, "No mapping found"); Req.Set_Request_URI ("test1"); Req.Set_Method ("GET"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, Servlet_Path, Req.Get_Servlet_Path, "Invalid servlet path"); Assert_Equals (T, Path_Info, Req.Get_Path_Info, "The request path info is invalid"); -- Check the response after the Test_Servlet1.Do_Get method execution. Resp.Read_Content (Result); Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status"); Assert_Equals (T, "URI: test1", Result, "Invalid content"); Req.Set_Method ("POST"); Forward (Dispatcher, Req, Resp); Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status, "Invalid status for an operation not implemented"); end Check_Request; -- ------------------------------ -- Test request dispatcher and servlet invocation -- ------------------------------ procedure Test_Request_Dispatcher (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces"); Check_Request (T, Ctx, "/home/test.jsf", "", "/home/test.jsf"); end Test_Request_Dispatcher; -- ------------------------------ -- Test mapping and servlet path on a request. -- ------------------------------ procedure Test_Servlet_Path (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces"); Check_Request (T, Ctx, "/p1/p2/p3/home/test.html", "/p1/p2/p3", "/home/test.html"); end Test_Servlet_Path; -- ------------------------------ -- Test add servlet -- ------------------------------ procedure Test_Add_Servlet (T : in out Test) is Ctx : Servlet_Registry; S1 : aliased Test_Servlet1; begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet"); begin Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); T.Assert (False, "No exception raised if the servlet is registered several times"); exception when Servlet_Error => null; end; end Test_Add_Servlet; -- ------------------------------ -- Test getting a resource path -- ------------------------------ procedure Test_Get_Resource (T : in out Test) is Ctx : Servlet_Registry; Conf : Applications.Config; S1 : aliased Test_Servlet1; Dir : constant String := "regtests/files"; Path : constant String := Util.Tests.Get_Path (Dir); begin Conf.Load_Properties ("regtests/view.properties"); Conf.Set ("view.dir", Path); Ctx.Set_Init_Parameters (Conf); Ctx.Add_Servlet ("Faces", S1'Unchecked_Access); -- Resource exist, check the returned path. declare P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml"); begin Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml", P, "Invalid resource path"); end; -- Resource does not exist declare P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml"); begin Assert_Equals (T, "", P, "Invalid resource path for missing resource"); end; end Test_Get_Resource; -- ------------------------------ -- Check that the mapping for the given URI matches the server. -- ------------------------------ procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access) is Map : constant Mapping_Access := Ctx.Find_Mapping (URI); begin if Map = null then T.Assert (Server = null, "No mapping returned for URI: " & URI); else T.Assert (Server /= null, "A mapping is returned for URI: " & URI); T.Assert (Map.Servlet = Server, "Invalid mapping returned for URI: " & URI); end if; end Check_Mapping; -- ------------------------------ -- Test session creation. -- ------------------------------ procedure Test_Create_Servlet (T : in out Test) is Ctx : Servlet_Registry; Map : Mapping_Access; begin Ctx.Add_Servlet (Name => "Faces", Server => S1'Access); Ctx.Add_Servlet (Name => "Text", Server => S2'Access); Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces"); Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text"); -- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access); Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access); Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access); Ctx.Mappings.Dump_Map (" "); T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access); T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access); T.Check_Mapping (Ctx, "/server/info", S1'Access); T.Check_Mapping (Ctx, "/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access); T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf"); end loop; Util.Measures.Report (St, "Find 1000 mapping (extension)"); end; T.Assert (Map /= null, "No mapping for 'joe.jsf'"); T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); T.Assert (Map.Servlet = S1'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2"); end loop; Util.Measures.Report (St, "Find 1000 mapping (path)"); end; T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'"); T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'"); T.Assert (Map.Servlet = S2'Access, "Invalid servlet"); -- Util.Measures.Report (St, "10 Session create"); end Test_Create_Servlet; package Caller is new Util.Test_Caller (Test, "Servlets"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping", Test_Create_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet", Test_Add_Servlet'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher", Test_Request_Dispatcher'Access); Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource", Test_Get_Resource'Access); Caller.Add_Test (Suite, "Test ASF.Requests.Get_Servlet_Path", Test_Servlet_Path'Access); end Add_Tests; end ASF.Servlets.Tests;
Add a unit test to check the request servlet path
Add a unit test to check the request servlet path
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
689e10214201b442c0563f6c0044e726ac1c28f2
regtests/security-testsuite.adb
regtests/security-testsuite.adb
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.OpenID.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; package body Security.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Security.OpenID.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
----------------------------------------------------------------------- -- Security testsuite - Ada Security Test suite -- 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 Security.OpenID.Tests; with Security.Permissions.Tests; with Security.Policies.Tests; with Security.OAuth.JWT.Tests; package body Security.Testsuite is Tests : aliased Util.Tests.Test_Suite; function Suite return Util.Tests.Access_Test_Suite is Ret : constant Util.Tests.Access_Test_Suite := Tests'Access; begin Security.OAuth.JWT.Tests.Add_Tests (Ret); Security.OpenID.Tests.Add_Tests (Ret); Security.Permissions.Tests.Add_Tests (Ret); Security.Policies.Tests.Add_Tests (Ret); return Ret; end Suite; end Security.Testsuite;
Add the new unit tests
Add the new unit tests
Ada
apache-2.0
Letractively/ada-security
c6c38e6110e52af546d364dfd7947b33c7835b3b
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions"); -- ------------------------------ -- 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. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- ------------------------------ 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 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. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- ------------------------------ 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;
Update the comments and logger
Update the comments and logger
Ada
apache-2.0
Letractively/ada-security
972754a8846641870a1d03d9d2e82bd7dca8797e
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Name_Array; Next_Role : Role_Type := Role_Type'First; end record; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)); Count : Natural := 0; Manager : Role_Policy_Access; end record; end Security.Policies.Roles;
Document the role based policy
Document the role based policy
Ada
apache-2.0
Letractively/ada-security
a892ba9ed59a9cdc4edf30fa49da65ce8c34d377
examples/train/src/trains.ads
examples/train/src/trains.ads
------------------------------------------------------------------------------ -- Bareboard drivers examples -- -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- This library is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 3, or (at your option) any later -- -- version. This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- ------------------------------------------------------------------------------ package Trains with SPARK_Mode is -- the railroad is composed of a set of one-way tracks, where each track -- joins two locations. A track has a length that is a multiple of an -- elementary distance. Num_Locations : constant := 39; type Location is new Positive range 1 .. Num_Locations; type Track is record From : Location; To : Location; Length : Positive; end record; Num_Tracks : constant := 51; type Track_Opt_Id is new Natural range 0 .. Num_Tracks; subtype Track_Id is Track_Opt_Id range 1 .. Num_Tracks; No_Track_Id : constant Track_Opt_Id := 0; -- example railroad going around between locations 1 to 5, with additional -- tracks from 1 to 3, 2 to 5 and 3 to 5. Tracks : array (Track_Id) of Track := (others => (1, 1, 1)); -- the map of previous tracks records for each location the tracks that -- precede it. This information should be consistent with the one in -- Tracks. Max_Num_Previous_Tracks : constant := 3; type Prev_Id is range 1 .. Max_Num_Previous_Tracks; type Track_Ids is array (Prev_Id) of Track_Opt_Id; Previous_Tracks : array (Location) of Track_Ids := (others => (0, 0, 0)); -- the railroad should respect the property that no track precedes itself function No_Track_Precedes_Itself return Boolean is (for all Track in Track_Id => (for all Id in Prev_Id => Previous_Tracks (Tracks (Track).From) (Id) /= Track)); -- a train is identified by its unique identifier. The position of each -- train is given by the starting track it's in (Track_Begin) and the -- position in this track (Pos_Begin), with the ending track it's in -- (Track_End) which can be the same as the starting track. A train -- can never be on three tracks. Max_Num_Trains : constant := 20; type Trains_Count is new Natural range 0 .. Max_Num_Trains; subtype Train_Id is Trains_Count range 1 .. Max_Num_Trains; Cur_Num_Trains : Trains_Count := 0; type Train_Position is record Track_Begin : Track_Id; Pos_Begin : Natural; Track_End : Track_Id; end record; Trains : array (Train_Id) of Train_Position; function Entering_A_Track (Position : Train_Position) return Boolean is (Position.Track_Begin /= Position.Track_End and then (for some Id in Prev_Id => Position.Track_End = Previous_Tracks (Tracks (Position.Track_Begin).From) (Id))); function Inside_A_Track (Position : Train_Position) return Boolean is (Position.Track_Begin = Position.Track_End); -- it should always hold that there is at most one train in every track -- segment function One_Train_At_Most_Per_Track return Boolean is (for all Train in Train_Id range 1 .. Cur_Num_Trains => (for all Other_Train in Train_Id range 1 .. Cur_Num_Trains => (if Other_Train /= Train then Trains (Train).Track_Begin /= Trains (Other_Train).Track_Begin and then Trains (Train).Track_Begin /= Trains (Other_Train).Track_End and then Trains (Train).Track_End /= Trains (Other_Train).Track_Begin and then Trains (Train).Track_End /= Trains (Other_Train).Track_End))); -- at each instant, the behavior of the train depends on the value of the -- signal on the track it's in and on the track ahead type Signal is (Green, Orange, Red); Track_Signals : array (Track_Id) of Signal; -- the signal should be Red on every track on which there is a train, and -- Orange on every previous track, unless already Red on that track. function Occupied_Tracks_On_Red return Boolean is (for all Train in Train_Id range 1 .. Cur_Num_Trains => Track_Signals (Trains (Train).Track_Begin) = Red and then Track_Signals (Trains (Train).Track_End) = Red); -- Return the Id'th track that precedes the ending track of the train function Get_Previous_Track (Position : Train_Position; Id : Prev_Id) return Track_Opt_Id is (Previous_Tracks (Tracks (Position.Track_End).From) (Id)); -- Return the Id'th track that precedes the starting track of the train, -- provided it is different from the ending track of the train function Get_Other_Previous_Track (Position : Train_Position; Id : Prev_Id) return Track_Opt_Id is (if Previous_Tracks (Tracks (Position.Track_Begin).From) (Id) = Position.Track_End then No_Track_Id else Previous_Tracks (Tracks (Position.Track_Begin).From) (Id)); function Is_Previous_Track (Position : Train_Position; Track : Track_Id) return Boolean is (for some Id in Prev_Id => Track = Get_Previous_Track (Position, Id) or else Track = Get_Other_Previous_Track (Position, Id)); function Previous_Tracks_On_Orange_Or_Red return Boolean is (for all Train in Train_Id range 1 .. Cur_Num_Trains => (for all Id in Prev_Id => (if Get_Previous_Track (Trains (Train), Id) /= No_Track_Id then Track_Signals (Get_Previous_Track (Trains (Train), Id)) in Orange | Red) and then (if Get_Other_Previous_Track (Trains (Train), Id) /= No_Track_Id then Track_Signals (Get_Other_Previous_Track (Trains (Train), Id)) in Orange | Red))); function Safe_Signaling return Boolean is (Occupied_Tracks_On_Red and then Previous_Tracks_On_Orange_Or_Red); -- valid movements of trains can be of 3 kinds: -- . moving inside one or two tracks -- . entering a new track -- . leaving a track -- The following functions correspond each to one of these kinds of -- movements. Function Valid_Move returns whether a movement is among -- these 3 kinds. function Moving_Inside_Current_Tracks (Cur_Position : Train_Position; New_Position : Train_Position) return Boolean is (Cur_Position.Track_Begin = New_Position.Track_Begin and then Cur_Position.Track_End = New_Position.Track_End); function Moving_To_A_New_Track (Cur_Position : Train_Position; New_Position : Train_Position) return Boolean is (Inside_A_Track (Cur_Position) and then Entering_A_Track (New_Position) and then Cur_Position.Track_Begin = New_Position.Track_End); function Moving_Away_From_Current_Track (Cur_Position : Train_Position; New_Position : Train_Position) return Boolean is (Entering_A_Track (Cur_Position) and then Inside_A_Track (New_Position) and then Cur_Position.Track_Begin = New_Position.Track_End); function Valid_Move (Cur_Position : Train_Position; New_Position : Train_Position) return Boolean is -- either the train keeps moving in the current tracks (Moving_Inside_Current_Tracks (Cur_Position, New_Position) or else -- or the train was inside a track and enters a new track Moving_To_A_New_Track (Cur_Position, New_Position) or else -- or the train was entering a track and leaves the previous one Moving_Away_From_Current_Track (Cur_Position, New_Position)); -- moving the train ahead along a valid movement can result in: -- . Full_Speed: the movement was performed, the position of the train -- (Trains) and the signals (Track_Signals) have been -- updated, and the train can continue full speed. -- . Slow_Down: Same as Full_Speed, but the train is entering an Orange -- track and should slow down. -- . Keep_Going: Same as Full_Speed, but the train should keep its -- current speed. -- . Stop: No movement performed, the train should stop here, -- prior to entering a Red track. type Move_Result is (Full_Speed, Slow_Down, Keep_Going, Stop); procedure Move (Train : Train_Id; New_Position : Train_Position; Result : out Move_Result) with Global => (Input => (Cur_Num_Trains, Previous_Tracks, Tracks), In_Out => (Trains, Track_Signals)), Pre => Train in 1 .. Cur_Num_Trains and then Valid_Move (Trains (Train), New_Position) and then One_Train_At_Most_Per_Track and then Safe_Signaling, Post => One_Train_At_Most_Per_Track and then Safe_Signaling; end Trains;
------------------------------------------------------------------------------ -- Bareboard drivers examples -- -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- This library is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 3, or (at your option) any later -- -- version. This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- ------------------------------------------------------------------------------ package Trains with SPARK_Mode is -- the railroad is composed of a set of one-way tracks, where each track -- joins two locations. A track has a length that is a multiple of an -- elementary distance. Num_Locations : constant := 39; type Location is new Positive range 1 .. Num_Locations; type Track is record From : Location; To : Location; Length : Positive; end record; Num_Tracks : constant := 51; type Track_Opt_Id is new Natural range 0 .. Num_Tracks; subtype Track_Id is Track_Opt_Id range 1 .. Num_Tracks; No_Track_Id : constant Track_Opt_Id := 0; -- example railroad going around between locations 1 to 5, with additional -- tracks from 1 to 3, 2 to 5 and 3 to 5. Tracks : array (Track_Id) of Track := (others => (1, 1, 1)); -- the map of previous tracks records for each location the tracks that -- precede it. This information should be consistent with the one in -- Tracks. Max_Num_Previous_Tracks : constant := 3; type Prev_Id is range 1 .. Max_Num_Previous_Tracks; type Track_Ids is array (Prev_Id) of Track_Opt_Id; Previous_Tracks : array (Location) of Track_Ids := (others => (0, 0, 0)); -- the railroad should respect the property that no track precedes itself function No_Track_Precedes_Itself return Boolean is (for all Track in Track_Id => (for all Id in Prev_Id => Previous_Tracks (Tracks (Track).From) (Id) /= Track)); -- a train is identified by its unique identifier. The position of each -- train is given by the starting track it's in (Track_Begin) and the -- position in this track (Pos_Begin), with the ending track it's in -- (Track_End) which can be the same as the starting track. A train -- can never be on three tracks. Max_Num_Trains : constant := 20; type Trains_Count is new Natural range 0 .. Max_Num_Trains; subtype Train_Id is Trains_Count range 1 .. Max_Num_Trains; Cur_Num_Trains : Trains_Count := 0; type Train_Position is record Track_Begin : Track_Id; Pos_Begin : Natural; Track_End : Track_Id; end record; Trains : array (Train_Id) of Train_Position; function Entering_A_Track (Position : Train_Position) return Boolean is (Position.Track_Begin /= Position.Track_End and then (for some Id in Prev_Id => Position.Track_End = Previous_Tracks (Tracks (Position.Track_Begin).From) (Id))); function Inside_A_Track (Position : Train_Position) return Boolean is (Position.Track_Begin = Position.Track_End); -- it should always hold that there is at most one train in every track -- segment function One_Train_At_Most_Per_Track return Boolean is (for all Train in Train_Id range 1 .. Cur_Num_Trains => (for all Other_Train in Train_Id range 1 .. Cur_Num_Trains => (if Other_Train /= Train then Trains (Train).Track_Begin /= Trains (Other_Train).Track_Begin and then Trains (Train).Track_Begin /= Trains (Other_Train).Track_End and then Trains (Train).Track_End /= Trains (Other_Train).Track_Begin and then Trains (Train).Track_End /= Trains (Other_Train).Track_End))); -- at each instant, the behavior of the train depends on the value of the -- signal on the track it's in and on the track ahead type Signal is (Green, Orange, Red); Track_Signals : array (Track_Id) of Signal; -- the signal should be Red on every track on which there is a train, and -- Orange on every previous track, unless already Red on that track. function Occupied_Tracks_On_Red return Boolean is (for all Train in Train_Id range 1 .. Cur_Num_Trains => Track_Signals (Trains (Train).Track_Begin) = Red and then Track_Signals (Trains (Train).Track_End) = Red); -- Return the Id'th track that precedes the ending track of the train function Get_Previous_Track (Position : Train_Position; Id : Prev_Id) return Track_Opt_Id is (Previous_Tracks (Tracks (Position.Track_End).From) (Id)); -- Return the Id'th track that precedes the starting track of the train, -- provided it is different from the ending track of the train function Get_Other_Previous_Track (Position : Train_Position; Id : Prev_Id) return Track_Opt_Id is (if Previous_Tracks (Tracks (Position.Track_Begin).From) (Id) = Position.Track_End then No_Track_Id else Previous_Tracks (Tracks (Position.Track_Begin).From) (Id)); function Is_Previous_Track (Position : Train_Position; Track : Track_Id) return Boolean is (for some Id in Prev_Id => Track = Get_Previous_Track (Position, Id) or else Track = Get_Other_Previous_Track (Position, Id)); function Previous_Tracks_On_Orange_Or_Red return Boolean is (for all Train in Train_Id range 1 .. Cur_Num_Trains => (for all Id in Prev_Id => (if Get_Previous_Track (Trains (Train), Id) /= No_Track_Id then Track_Signals (Get_Previous_Track (Trains (Train), Id)) in Orange | Red) and then (if Get_Other_Previous_Track (Trains (Train), Id) /= No_Track_Id then Track_Signals (Get_Other_Previous_Track (Trains (Train), Id)) in Orange | Red))); function Safe_Signaling return Boolean is (Occupied_Tracks_On_Red and then Previous_Tracks_On_Orange_Or_Red); -- valid movements of trains can be of 3 kinds: -- . moving inside one or two tracks -- . entering a new track -- . leaving a track -- The following functions correspond each to one of these kinds of -- movements. Function Valid_Move returns whether a movement is among -- these 3 kinds. function Moving_Inside_Current_Tracks (Cur_Position : Train_Position; New_Position : Train_Position) return Boolean is (Cur_Position.Track_Begin = New_Position.Track_Begin and then Cur_Position.Track_End = New_Position.Track_End); function Moving_To_A_New_Track (Cur_Position : Train_Position; New_Position : Train_Position) return Boolean is (Inside_A_Track (Cur_Position) and then Entering_A_Track (New_Position) and then Cur_Position.Track_Begin = New_Position.Track_End); function Moving_Away_From_Current_Track (Cur_Position : Train_Position; New_Position : Train_Position) return Boolean is (Entering_A_Track (Cur_Position) and then Inside_A_Track (New_Position) and then Cur_Position.Track_Begin = New_Position.Track_End); function Valid_Move (Cur_Position : Train_Position; New_Position : Train_Position) return Boolean is -- either the train keeps moving in the current tracks (Moving_Inside_Current_Tracks (Cur_Position, New_Position) or else -- or the train was inside a track and enters a new track Moving_To_A_New_Track (Cur_Position, New_Position) or else -- or the train was entering a track and leaves the previous one Moving_Away_From_Current_Track (Cur_Position, New_Position)); -- moving the train ahead along a valid movement can result in: -- . Full_Speed: the movement was performed, the position of the train -- (Trains) and the signals (Track_Signals) have been -- updated, and the train can continue full speed. -- . Slow_Down: Same as Full_Speed, but the train is entering an Orange -- track and should slow down. -- . Keep_Going: Same as Full_Speed, but the train should keep its -- current speed. -- . Stop: No movement performed, the train should stop here, -- prior to entering a Red track. type Move_Result is (Full_Speed, Slow_Down, Keep_Going, Stop); procedure Move (Train : Train_Id; New_Position : Train_Position; Result : out Move_Result) with Global => (Input => (Cur_Num_Trains, Previous_Tracks, Tracks), In_Out => (Trains, Track_Signals)), Pre => Train <= Cur_Num_Trains and then Valid_Move (Trains (Train), New_Position) and then One_Train_At_Most_Per_Track and then Safe_Signaling, Post => One_Train_At_Most_Per_Track and then Safe_Signaling; end Trains;
Fix a compilation warning in the Trains demo
Fix a compilation warning in the Trains demo
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
c93c7c19cbd69c6d076f3db76c14d53a19cc27c5
src/portscan-buildcycle-ports.adb
src/portscan-buildcycle-ports.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package body PortScan.Buildcycle.Ports is --------------------- -- build_package -- --------------------- function build_package (id : builders; sequence_id : port_id; interactive : Boolean := False; interphase : String := "") return Boolean is R : Boolean; break_phase : constant phases := valid_test_phase (interphase); run_selftest : constant Boolean := Unix.env_variable_defined (selftest); begin trackers (id).seq_id := sequence_id; trackers (id).loglines := 0; if uselog then if not initialize_log (id) then finalize_log (id); return False; end if; end if; for phase in phases'Range loop phase_trackers (id) := phase; case phase is when check_sanity | fetch | checksum | extract | patch | pkg_package => R := exec_phase_generic (id, phase); when pkg_depends | fetch_depends | extract_depends | patch_depends | build_depends | lib_depends | run_depends => R := exec_phase_depends (id, phase); when configure => if testing then if lock_localbase then set_localbase_protection (id, True); end if; mark_file_system (id, "preconfig"); end if; R := exec_phase_generic (id, phase); when build => R := exec_phase_build (id); when test => if testing and run_selftest then R := exec_phase_generic (id, phase); end if; when stage => if testing then mark_file_system (id, "prestage"); end if; R := exec_phase_generic (id, phase); when install_mtree | install | check_plist => if testing then R := exec_phase_generic (id, phase); end if; when deinstall => if testing then R := exec_phase_deinstall (id); end if; end case; exit when R = False; exit when interactive and then phase = break_phase; end loop; if uselog then finalize_log (id); end if; if interactive then interact_with_builder (id); end if; return R; end build_package; --------------------------- -- valid_test_phase #1 -- --------------------------- function valid_test_phase (afterphase : String) return phases is begin if afterphase = "extract" then return extract; elsif afterphase = "patch" then return patch; elsif afterphase = "configure" then return configure; elsif afterphase = "build" then return build; elsif afterphase = "stage" then return check_plist; elsif afterphase = "install" then return install; elsif afterphase = "deinstall" then return deinstall; else return check_sanity; end if; end valid_test_phase; ----------------- -- phase2str -- ----------------- function phase2str (phase : phases) return String is begin case phase is when check_sanity => return "check-sanity"; when pkg_depends => return "pkg-depends"; when fetch_depends => return "fetch-depends"; when fetch => return "fetch"; when checksum => return "checksum"; when extract_depends => return "extract-depends"; when extract => return "extract"; when patch_depends => return "patch-depends"; when patch => return "patch"; when build_depends => return "build-depends"; when lib_depends => return "lib-depends"; when configure => return "configure"; when build => return "build"; when run_depends => return "run-depends"; when stage => return "stage"; when test => return "test"; when pkg_package => return "package"; when install_mtree => return "install-mtree"; when install => return "install"; when deinstall => return "deinstall"; when check_plist => return "check-plist"; end case; end phase2str; ------------------------------- -- max_time_without_output -- ------------------------------- function max_time_without_output (phase : phases) return execution_limit is base : Integer; begin case phase is when check_sanity => base := 1; when pkg_depends => base := 3; when fetch_depends => base := 3; when fetch | checksum => return 480; -- 8 hours when extract_depends => base := 3; when extract => base := 20; when patch_depends => base := 3; when patch => base := 3; when build_depends => base := 5; when lib_depends => base := 5; when configure => base := 15; when build => base := 25; -- for gcc linking, tex when run_depends => base := 15; -- octave-forge is driver when stage => base := 20; -- desire 15 but too many rogue builders-in-stage when test => base := 25; when check_plist => base := 10; -- For packages with thousands of files when pkg_package => base := 80; when install_mtree => base := 3; when install => base := 10; when deinstall => base := 10; end case; declare multiplier_x10 : constant Positive := timeout_multiplier_x10; begin return execution_limit (base * multiplier_x10 / 10); end; end max_time_without_output; -------------------------- -- exec_phase_generic -- -------------------------- function exec_phase_generic (id : builders; phase : phases) return Boolean is time_limit : execution_limit := max_time_without_output (phase); begin return exec_phase (id => id, phase => phase, time_limit => time_limit); end exec_phase_generic; -------------------------- -- exec_phase_depends -- -------------------------- function exec_phase_depends (id : builders; phase : phases) return Boolean is time_limit : execution_limit := max_time_without_output (phase); phaseenv : String := "USE_PACKAGE_DEPENDS_ONLY=1"; begin return exec_phase (id => id, phase => phase, phaseenv => phaseenv, time_limit => time_limit, depends_phase => True); end exec_phase_depends; ------------------ -- exec_phase -- ------------------ function exec_phase (id : builders; phase : phases; time_limit : execution_limit; phaseenv : String := ""; depends_phase : Boolean := False; skip_header : Boolean := False; skip_footer : Boolean := False) return Boolean is root : constant String := get_root (id); port_flags : String := " NO_DEPENDS=yes "; pid : port_id := trackers (id).seq_id; catport : constant String := get_catport (all_ports (pid)); result : Boolean; timed_out : Boolean; begin if testing or else depends_phase then port_flags := (others => LAT.Space); end if; -- Nasty, we have to switch open and close the log file for each -- phase because we have to switch between File_Type and File -- Descriptors. I can't find a safe way to get the File Descriptor -- out of the File type. if uselog then if not skip_header then log_phase_begin (phase2str (phase), id); end if; TIO.Close (trackers (id).log_handle); end if; declare command : constant String := chroot & root & environment_override & phaseenv & port_flags & chroot_make_program & " -C " & dir_ports & "/" & catport & " " & phase2str (phase); begin result := generic_execute (id, command, timed_out, time_limit); end; -- Reopen the log. I guess we can leave off the exception check -- since it's been passing before if uselog then TIO.Open (File => trackers (id).log_handle, Mode => TIO.Append_File, Name => log_name (trackers (id).seq_id)); if timed_out then TIO.Put_Line (trackers (id).log_handle, "### Watchdog killed runaway process! (no activity for" & time_limit'Img & " minutes) ###"); end if; if not skip_footer then log_phase_end (id); end if; end if; return result; end exec_phase; ------------------------ -- exec_phase_build -- ------------------------ function exec_phase_build (id : builders) return Boolean is time_limit : execution_limit := max_time_without_output (build); passed : Boolean; begin passed := exec_phase (id => id, phase => build, time_limit => time_limit, skip_header => False, skip_footer => True); if testing and then passed then if lock_localbase then set_localbase_protection (id, False); end if; passed := detect_leftovers_and_MIA (id, "preconfig", "between port configure and build"); end if; if uselog then log_phase_end (id); end if; return passed; end exec_phase_build; ---------------------------- -- exec_phase_deinstall -- ---------------------------- function exec_phase_deinstall (id : builders) return Boolean is time_limit : execution_limit := max_time_without_output (deinstall); result : Boolean; begin -- This is only run during "testing" so assume that. if uselog then log_phase_begin (phase2str (deinstall), id); log_linked_libraries (id); end if; result := exec_phase (id => id, phase => deinstall, time_limit => time_limit, skip_header => True, skip_footer => True); if not result then if uselog then log_phase_end (id); end if; return False; end if; if uselog then result := detect_leftovers_and_MIA (id, "prestage", "between staging and package deinstallation"); log_phase_end (id); end if; return result; end exec_phase_deinstall; ---------------------- -- builder_status -- ---------------------- function builder_status (id : builders; shutdown : Boolean := False; idle : Boolean := False) return Display.builder_rec is phasestr : constant String := phase2str (phase_trackers (id)); begin return builder_status_core (id => id, shutdown => shutdown, idle => idle, phasestr => phasestr); end builder_status; ------------------------ -- last_build_phase -- ------------------------ function last_build_phase (id : builders) return String is begin return phase2str (phase => phase_trackers (id)); end last_build_phase; end PortScan.Buildcycle.Ports;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package body PortScan.Buildcycle.Ports is --------------------- -- build_package -- --------------------- function build_package (id : builders; sequence_id : port_id; interactive : Boolean := False; interphase : String := "") return Boolean is R : Boolean; break_phase : constant phases := valid_test_phase (interphase); run_selftest : constant Boolean := Unix.env_variable_defined (selftest); begin trackers (id).seq_id := sequence_id; trackers (id).loglines := 0; if uselog then if not initialize_log (id) then finalize_log (id); return False; end if; end if; for phase in phases'Range loop phase_trackers (id) := phase; case phase is when check_sanity | fetch | checksum | extract | patch | pkg_package => R := exec_phase_generic (id, phase); when pkg_depends | fetch_depends | extract_depends | patch_depends | build_depends | lib_depends | run_depends => R := exec_phase_depends (id, phase); when configure => if testing then if lock_localbase then set_localbase_protection (id, True); end if; mark_file_system (id, "preconfig"); end if; R := exec_phase_generic (id, phase); when build => R := exec_phase_build (id); when test => if testing and run_selftest then R := exec_phase_generic (id, phase); end if; when stage => if testing then mark_file_system (id, "prestage"); end if; R := exec_phase_generic (id, phase); when install_mtree | install | check_plist => if testing then R := exec_phase_generic (id, phase); end if; when deinstall => if testing then R := exec_phase_deinstall (id); end if; end case; exit when R = False; exit when interactive and then phase = break_phase; end loop; if uselog then finalize_log (id); end if; if interactive then interact_with_builder (id); end if; return R; end build_package; --------------------------- -- valid_test_phase #1 -- --------------------------- function valid_test_phase (afterphase : String) return phases is begin if afterphase = "extract" then return extract; elsif afterphase = "patch" then return patch; elsif afterphase = "configure" then return configure; elsif afterphase = "build" then return build; elsif afterphase = "stage" then return check_plist; elsif afterphase = "install" then return install; elsif afterphase = "deinstall" then return deinstall; else return check_sanity; end if; end valid_test_phase; ----------------- -- phase2str -- ----------------- function phase2str (phase : phases) return String is begin case phase is when check_sanity => return "check-sanity"; when pkg_depends => return "pkg-depends"; when fetch_depends => return "fetch-depends"; when fetch => return "fetch"; when checksum => return "checksum"; when extract_depends => return "extract-depends"; when extract => return "extract"; when patch_depends => return "patch-depends"; when patch => return "patch"; when build_depends => return "build-depends"; when lib_depends => return "lib-depends"; when configure => return "configure"; when build => return "build"; when run_depends => return "run-depends"; when stage => return "stage"; when test => return "test"; when pkg_package => return "package"; when install_mtree => return "install-mtree"; when install => return "install"; when deinstall => return "deinstall"; when check_plist => return "check-plist"; end case; end phase2str; ------------------------------- -- max_time_without_output -- ------------------------------- function max_time_without_output (phase : phases) return execution_limit is base : Integer; begin case phase is when check_sanity => base := 1; when pkg_depends => base := 3; when fetch_depends => base := 3; when fetch | checksum => return 480; -- 8 hours when extract_depends => base := 3; when extract => base := 20; when patch_depends => base := 3; when patch => base := 3; when build_depends => base := 11; -- for texlive when lib_depends => base := 5; when configure => base := 15; when build => base := 25; -- for gcc linking, tex when run_depends => base := 15; -- octave-forge is driver when stage => base := 20; -- desire 15 but too many rogue builders-in-stage when test => base := 25; when check_plist => base := 10; -- For packages with thousands of files when pkg_package => base := 80; when install_mtree => base := 3; when install => base := 10; when deinstall => base := 10; end case; declare multiplier_x10 : constant Positive := timeout_multiplier_x10; begin return execution_limit (base * multiplier_x10 / 10); end; end max_time_without_output; -------------------------- -- exec_phase_generic -- -------------------------- function exec_phase_generic (id : builders; phase : phases) return Boolean is time_limit : execution_limit := max_time_without_output (phase); begin return exec_phase (id => id, phase => phase, time_limit => time_limit); end exec_phase_generic; -------------------------- -- exec_phase_depends -- -------------------------- function exec_phase_depends (id : builders; phase : phases) return Boolean is time_limit : execution_limit := max_time_without_output (phase); phaseenv : String := "USE_PACKAGE_DEPENDS_ONLY=1"; begin return exec_phase (id => id, phase => phase, phaseenv => phaseenv, time_limit => time_limit, depends_phase => True); end exec_phase_depends; ------------------ -- exec_phase -- ------------------ function exec_phase (id : builders; phase : phases; time_limit : execution_limit; phaseenv : String := ""; depends_phase : Boolean := False; skip_header : Boolean := False; skip_footer : Boolean := False) return Boolean is root : constant String := get_root (id); port_flags : String := " NO_DEPENDS=yes "; pid : port_id := trackers (id).seq_id; catport : constant String := get_catport (all_ports (pid)); result : Boolean; timed_out : Boolean; begin if testing or else depends_phase then port_flags := (others => LAT.Space); end if; -- Nasty, we have to switch open and close the log file for each -- phase because we have to switch between File_Type and File -- Descriptors. I can't find a safe way to get the File Descriptor -- out of the File type. if uselog then if not skip_header then log_phase_begin (phase2str (phase), id); end if; TIO.Close (trackers (id).log_handle); end if; declare command : constant String := chroot & root & environment_override & phaseenv & port_flags & chroot_make_program & " -C " & dir_ports & "/" & catport & " " & phase2str (phase); begin result := generic_execute (id, command, timed_out, time_limit); end; -- Reopen the log. I guess we can leave off the exception check -- since it's been passing before if uselog then TIO.Open (File => trackers (id).log_handle, Mode => TIO.Append_File, Name => log_name (trackers (id).seq_id)); if timed_out then TIO.Put_Line (trackers (id).log_handle, "### Watchdog killed runaway process! (no activity for" & time_limit'Img & " minutes) ###"); end if; if not skip_footer then log_phase_end (id); end if; end if; return result; end exec_phase; ------------------------ -- exec_phase_build -- ------------------------ function exec_phase_build (id : builders) return Boolean is time_limit : execution_limit := max_time_without_output (build); passed : Boolean; begin passed := exec_phase (id => id, phase => build, time_limit => time_limit, skip_header => False, skip_footer => True); if testing and then passed then if lock_localbase then set_localbase_protection (id, False); end if; passed := detect_leftovers_and_MIA (id, "preconfig", "between port configure and build"); end if; if uselog then log_phase_end (id); end if; return passed; end exec_phase_build; ---------------------------- -- exec_phase_deinstall -- ---------------------------- function exec_phase_deinstall (id : builders) return Boolean is time_limit : execution_limit := max_time_without_output (deinstall); result : Boolean; begin -- This is only run during "testing" so assume that. if uselog then log_phase_begin (phase2str (deinstall), id); log_linked_libraries (id); end if; result := exec_phase (id => id, phase => deinstall, time_limit => time_limit, skip_header => True, skip_footer => True); if not result then if uselog then log_phase_end (id); end if; return False; end if; if uselog then result := detect_leftovers_and_MIA (id, "prestage", "between staging and package deinstallation"); log_phase_end (id); end if; return result; end exec_phase_deinstall; ---------------------- -- builder_status -- ---------------------- function builder_status (id : builders; shutdown : Boolean := False; idle : Boolean := False) return Display.builder_rec is phasestr : constant String := phase2str (phase_trackers (id)); begin return builder_status_core (id => id, shutdown => shutdown, idle => idle, phasestr => phasestr); end builder_status; ------------------------ -- last_build_phase -- ------------------------ function last_build_phase (id : builders) return String is begin return phase2str (phase => phase_trackers (id)); end last_build_phase; end PortScan.Buildcycle.Ports;
set the base time limit for build depends to 11 minute (#72)
set the base time limit for build depends to 11 minute (#72)
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
a4b42ff184868d6de5d1f8d4d94febadcb328328
asfunit/asf-server-tests.adb
asfunit/asf-server-tests.adb
----------------------------------------------------------------------- -- asf.server -- ASF Server -- 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. ----------------------------------------------------------------------- package body ASF.Server.Tests is procedure Set_Context (Context : in ASF.Servlets.Servlet_Registry_Access) is C : Request_Context; begin C.Application := Context; C.Process := null; ASF.Server.Set_Context (C); end Set_Context; end ASF.Server.Tests;
----------------------------------------------------------------------- -- asf.server -- ASF Server -- 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. ----------------------------------------------------------------------- package body ASF.Server.Tests is procedure Set_Context (Context : in ASF.Servlets.Servlet_Registry_Access) is C : Request_Context; begin C.Application := Context; C.Request := null; C.Response := null; ASF.Server.Set_Context (C); end Set_Context; end ASF.Server.Tests;
Fix compilation of asfunit
Fix compilation of asfunit
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
aa103e2a28a3d54b4b8d3a075aa0197b52a2f0c0
src/gl/interface/gl-types-colors.ads
src/gl/interface/gl-types-colors.ads
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Pointers; package GL.Types.Colors is pragma Preelaborate; type Color_Index is (R, G, B, A); subtype Basic_Color_Index is Color_Index range R .. B; subtype Component is Single range 0.0 .. 1.0; type Color is array (Color_Index) of aliased Component; type Basic_Color is array (Basic_Color_Index) of Component; pragma Convention (C, Color); pragma Convention (C, Basic_Color); type Enabled_Color is array (Color_Index) of Boolean with Convention => C; type Color_Array is array (Size range <>) of aliased Color; type Basic_Color_Array is array (Size range <>) of aliased Basic_Color; package Color_Pointers is new Interfaces.C.Pointers (Size, Color, Color_Array, Color'(others => 0.0)); package Basic_Color_Pointers is new Interfaces.C.Pointers (Size, Basic_Color, Basic_Color_Array, Basic_Color'(others => 0.0)); end GL.Types.Colors;
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Pointers; package GL.Types.Colors is pragma Preelaborate; type Color_Index is (R, G, B, A); subtype Component is Single range 0.0 .. 1.0; type Color is array (Color_Index) of aliased Component; pragma Convention (C, Color); type Enabled_Color is array (Color_Index) of Boolean with Convention => C; type Color_Array is array (Size range <>) of aliased Color; package Color_Pointers is new Interfaces.C.Pointers (Size, Color, Color_Array, Color'(others => 0.0)); end GL.Types.Colors;
Remove unused type Basic_Color
gl: Remove unused type Basic_Color Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
f2d965dcdf7d1673add632387d31d96e03f118d3
src/base/log/util-log-appenders-rolling_files.ads
src/base/log/util-log-appenders-rolling_files.ads
----------------------------------------------------------------------- -- util-log-appenders-rolling_files -- Rolling file log appenders -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Util.Properties; private with Util.Refs; private with Util.Files.Rolling; -- === Rolling file appender === -- The `RollingFile` appender recognises the following configurations: -- -- | Name | Description | -- | -------------- | -------------------------------------------------------------- | -- | layout | Defines the format of the message printed by the appender. | -- | level | Defines the minimum level above which messages are printed. | -- | fileName | The name of the file to write to. If the file, or any of its parent | -- | | directories, do not exist, they will be created. | -- | filePattern | The pattern of the file name of the archived log file. The pattern | -- | | can contain '%i' which are replaced by a counter incremented at each | -- | | rollover, a '%d' is replaced by a date pattern. | -- | append | When 'true' or '1', the file is opened in append mode otherwise | -- | | it is truncated (the default is to truncate). | -- | immediateFlush | When 'true' or '1', the file is flushed after each message log. | -- | | Immediate flush is useful in some situations to have the log file | -- | | updated immediately at the expense of slowing down the processing | -- | | of logs. | -- | policy | The triggering policy which drives when a rolling is performed. | -- | | Possible values are: `none`, `size`, `time` | -- | strategy | The strategy to use to determine the name and location of the | -- | | archive file. Possible values are: `ascending`, `descending`, and | -- | | `direct`. Default is `ascending`. | -- | policyInterval | How often a rollover should occur based on the most specific time | -- | | unit in the date pattern. For example, with a date pattern with | -- | | hours as the most specific item and and increment of 4 rollovers | -- | | would occur every 4 hours. The default value is 1. | -- | policyMin | The minimum value of the counter. The default value is 1. | -- | policyMax | The maximum value of the counter. Once this values is reached older | -- | | archives will be deleted on subsequent rollovers. The default | -- | | value is 7. | -- | minSize | The minimum size the file must have to roll over. | package Util.Log.Appenders.Rolling_Files is -- ------------------------------ -- File appender -- ------------------------------ type File_Appender (Length : Positive) is new Appender with private; type File_Appender_Access is access all File_Appender'Class; overriding procedure Append (Self : in out File_Appender; Message : in Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Level : in Level_Type; Logger : in String); -- Flush the log events. overriding procedure Flush (Self : in out File_Appender); -- Flush and close the file. overriding procedure Finalize (Self : in out File_Appender); -- Create a file appender and configure it according to the properties function Create (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; private type File_Entity is new Util.Refs.Ref_Entity with record Output : Ada.Text_IO.File_Type; end record; type File_Access is access all File_Entity; -- Finalize the referenced object. This is called before the object is freed. overriding procedure Finalize (Object : in out File_Entity); package File_Refs is new Util.Refs.References (File_Entity, File_Access); protected type Rolling_File is procedure Initialize (Name : in String; Base : in String; Properties : in Util.Properties.Manager); procedure Openlog (File : out File_Refs.Ref); procedure Flush (File : out File_Refs.Ref); procedure Closelog; private Manager : Util.Files.Rolling.File_Manager; Current : File_Refs.Ref; Append : Boolean; end Rolling_File; type File_Appender (Length : Positive) is new Appender (Length) with record Immediate_Flush : Boolean := False; File : Rolling_File; end record; end Util.Log.Appenders.Rolling_Files;
----------------------------------------------------------------------- -- util-log-appenders-rolling_files -- Rolling file log appenders -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Util.Properties; private with Util.Refs; private with Util.Files.Rolling; -- === Rolling file appender === -- The `RollingFile` appender recognises the following configurations: -- -- | Name | Description | -- | -------------- | -------------------------------------------------------------- | -- | layout | Defines the format of the message printed by the appender. | -- | level | Defines the minimum level above which messages are printed. | -- | fileName | The name of the file to write to. If the file, or any of its parent | -- | | directories, do not exist, they will be created. | -- | filePattern | The pattern of the file name of the archived log file. The pattern | -- | | can contain '%i' which are replaced by a counter incremented at each | -- | | rollover, a '%d' is replaced by a date pattern. | -- | append | When 'true' or '1', the file is opened in append mode otherwise | -- | | it is truncated (the default is to truncate). | -- | immediateFlush | When 'true' or '1', the file is flushed after each message log. | -- | | Immediate flush is useful in some situations to have the log file | -- | | updated immediately at the expense of slowing down the processing | -- | | of logs. | -- | policy | The triggering policy which drives when a rolling is performed. | -- | | Possible values are: `none`, `size`, `time`, `size-time` | -- | strategy | The strategy to use to determine the name and location of the | -- | | archive file. Possible values are: `ascending`, `descending`, and | -- | | `direct`. Default is `ascending`. | -- | policyInterval | How often a rollover should occur based on the most specific time | -- | | unit in the date pattern. This indicates the period in seconds | -- | | to check for pattern change in the `time` or `size-time` policy. | -- | policyMin | The minimum value of the counter. The default value is 1. | -- | policyMax | The maximum value of the counter. Once this values is reached older | -- | | archives will be deleted on subsequent rollovers. The default | -- | | value is 7. | -- | minSize | The minimum size the file must have to roll over. | -- -- A typical rolling file configuration would look like: -- -- log4j.rootCategory=DEBUG,applogger,apperror -- log4j.appender.applogger=RollingFile -- log4j.appender.applogger.layout=level-message -- log4j.appender.applogger.level=DEBUG -- log4j.appender.applogger.fileName=logs/debug.log -- log4j.appender.applogger.filePattern=logs/debug-%d{YYYY-MM}/debug-%{dd}-%i.log -- log4j.appender.applogger.strategy=descending -- log4j.appender.applogger.policy=time -- log4j.appender.applogger.policyMax=10 -- log4j.appender.apperror=RollingFile -- log4j.appender.apperror.layout=level-message -- log4j.appender.apperror.level=ERROR -- log4j.appender.apperror.fileName=logs/error.log -- log4j.appender.apperror.filePattern=logs/error-%d{YYYY-MM}/error-%{dd}.log -- log4j.appender.apperror.strategy=descending -- log4j.appender.apperror.policy=time -- -- With this configuration, the error messages are written in the `error.log` file and -- they are rotated on a day basis and moved in a directory whose name contains the year -- and month number. At the same time, debug messages are written in the `debug.log` -- file. package Util.Log.Appenders.Rolling_Files is -- ------------------------------ -- File appender -- ------------------------------ type File_Appender (Length : Positive) is new Appender with private; type File_Appender_Access is access all File_Appender'Class; overriding procedure Append (Self : in out File_Appender; Message : in Util.Strings.Builders.Builder; Date : in Ada.Calendar.Time; Level : in Level_Type; Logger : in String); -- Flush the log events. overriding procedure Flush (Self : in out File_Appender); -- Flush and close the file. overriding procedure Finalize (Self : in out File_Appender); -- Create a file appender and configure it according to the properties function Create (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; private type File_Entity is new Util.Refs.Ref_Entity with record Output : Ada.Text_IO.File_Type; end record; type File_Access is access all File_Entity; -- Finalize the referenced object. This is called before the object is freed. overriding procedure Finalize (Object : in out File_Entity); package File_Refs is new Util.Refs.References (File_Entity, File_Access); protected type Rolling_File is procedure Initialize (Name : in String; Base : in String; Properties : in Util.Properties.Manager); procedure Openlog (File : out File_Refs.Ref); procedure Flush (File : out File_Refs.Ref); procedure Closelog; private Manager : Util.Files.Rolling.File_Manager; Current : File_Refs.Ref; Append : Boolean; end Rolling_File; type File_Appender (Length : Positive) is new Appender (Length) with record Immediate_Flush : Boolean := False; File : Rolling_File; end record; end Util.Log.Appenders.Rolling_Files;
Update the documentation for rolling file appender
Update the documentation for rolling file appender
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
410fab181da593a09455b7cb9fdc80db62957e7a
src/asf-lifecycles.adb
src/asf-lifecycles.adb
----------------------------------------------------------------------- -- asf-lifecycles -- Lifecycle -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Contexts.Exceptions; package body ASF.Lifecycles is -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Controller : in out Lifecycle; App : access ASF.Applications.Main.Application'Class) is begin -- Create the phase controllers. Lifecycle'Class (Controller).Create_Phase_Controllers; -- Initialize the phase controllers. for Phase in Controller.Controllers'Range loop Controller.Controllers (Phase).Initialize (App); end loop; end Initialize; -- ------------------------------ -- Finalize the lifecycle handler, freeing the allocated storage. -- ------------------------------ overriding procedure Finalize (Controller : in out Lifecycle) is procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class, Phase_Controller_Access); begin -- Free the phase controllers. for Phase in Controller.Controllers'Range loop Free (Controller.Controllers (Phase)); end loop; end Finalize; -- ------------------------------ -- Set the controller to be used for the given phase. -- ------------------------------ procedure Set_Controller (Controller : in out Lifecycle; Phase : in Phase_Type; Instance : in Phase_Controller_Access) is begin Controller.Controllers (Phase) := Instance; end Set_Controller; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Contexts.Exceptions.Exception_Handler_Access; use ASF.Events.Phases; begin for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop if Context.Get_Render_Response or Context.Get_Response_Completed then return; end if; begin Controller.Controllers (Phase).Execute (Context); exception when E : others => Context.Queue_Exception (E); end; -- If exceptions have been raised and queued during the current phase, process them. -- An exception handler could use them to redirect the current request to another -- page or navigate to a specific view. declare Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access := Context.Get_Exception_Handler; begin if Ex /= null then Ex.Handle; end if; end; end loop; end Execute; -- ------------------------------ -- Render the response by executing the response phase. -- ------------------------------ procedure Render (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin Controller.Controllers (ASF.Events.Phases.RENDER_RESPONSE).Execute (Context); end Render; end ASF.Lifecycles;
----------------------------------------------------------------------- -- asf-lifecycles -- Lifecycle -- 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 ASF.Contexts.Exceptions; package body ASF.Lifecycles is -- ------------------------------ -- Initialize the the lifecycle handler. -- ------------------------------ procedure Initialize (Controller : in out Lifecycle; App : access ASF.Applications.Main.Application'Class) is begin -- Create the phase controllers. Lifecycle'Class (Controller).Create_Phase_Controllers; -- Initialize the phase controllers. for Phase in Controller.Controllers'Range loop Controller.Controllers (Phase).Initialize (App); end loop; end Initialize; -- ------------------------------ -- Finalize the lifecycle handler, freeing the allocated storage. -- ------------------------------ overriding procedure Finalize (Controller : in out Lifecycle) is procedure Free is new Ada.Unchecked_Deallocation (Phase_Controller'Class, Phase_Controller_Access); begin -- Free the phase controllers. for Phase in Controller.Controllers'Range loop Free (Controller.Controllers (Phase)); end loop; end Finalize; -- ------------------------------ -- Set the controller to be used for the given phase. -- ------------------------------ procedure Set_Controller (Controller : in out Lifecycle; Phase : in Phase_Type; Instance : in Phase_Controller_Access) is begin Controller.Controllers (Phase) := Instance; end Set_Controller; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Execute (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Contexts.Exceptions.Exception_Handler_Access; use ASF.Events.Phases; begin for Phase in RESTORE_VIEW .. INVOKE_APPLICATION loop if Context.Get_Render_Response or Context.Get_Response_Completed then return; end if; begin Context.Set_Current_Phase (Phase); Controller.Controllers (Phase).Execute (Context); exception when E : others => Context.Queue_Exception (E); end; -- If exceptions have been raised and queued during the current phase, process them. -- An exception handler could use them to redirect the current request to another -- page or navigate to a specific view. declare Ex : constant ASF.Contexts.Exceptions.Exception_Handler_Access := Context.Get_Exception_Handler; begin if Ex /= null then Ex.Handle; end if; end; end loop; end Execute; -- ------------------------------ -- Render the response by executing the response phase. -- ------------------------------ procedure Render (Controller : in Lifecycle; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin Context.Set_Current_Phase (ASF.Events.Phases.RENDER_RESPONSE); Controller.Controllers (ASF.Events.Phases.RENDER_RESPONSE).Execute (Context); end Render; end ASF.Lifecycles;
Set the lifecycle phase in the faces context before executing each lifecycle operation
Set the lifecycle phase in the faces context before executing each lifecycle operation
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
6e960049027cf7e53b7898622df62c32f19152ed
src/gl/implementation/gl-objects-shaders.adb
src/gl/implementation/gl-objects-shaders.adb
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Strings; with GL.API; with GL.Enums; package body GL.Objects.Shaders is procedure Set_Source (Subject : Shader; Source : String) is C_Shader_Source : C.Strings.chars_ptr := C.Strings.New_String (Source); C_Source : constant Low_Level.CharPtr_Array := (1 => C_Shader_Source); Lengths : constant Low_Level.Int_Array := (1 => Source'Length); begin API.Shader_Source (Subject.Reference.GL_Id, 1, C_Source, Lengths); C.Strings.Free (C_Shader_Source); Raise_Exception_On_OpenGL_Error; end Set_Source; function Source (Subject : Shader) return String is Source_Length : Size := 0; begin API.Get_Shader_Param (Subject.Reference.GL_Id, Enums.Shader_Source_Length, Source_Length); declare Shader_Source : String (1 .. Integer (Source_Length)); -- do not care that we do not assign a value. pragma Warnings (Off, Shader_Source); C_Shader_Source : C.Strings.chars_ptr := C.Strings.New_String (Shader_Source); Actual_Length : Size; begin API.Get_Shader_Source (Subject.Reference.GL_Id, Source_Length, Actual_Length, C_Shader_Source); Shader_Source := C.Strings.Value (C_Shader_Source, C.size_t (Actual_Length)); C.Strings.Free (C_Shader_Source); return Shader_Source; end; end Source; procedure Compile (Subject : Shader) is begin API.Compile_Shader (Subject.Reference.GL_Id); Raise_Exception_On_OpenGL_Error; end Compile; procedure Release_Shader_Compiler renames API.Release_Shader_Compiler; function Compile_Status (Subject : Shader) return Boolean is Value : Int := 0; begin API.Get_Shader_Param (Subject.Reference.GL_Id, Enums.Compile_Status, Value); return Value /= 0; end Compile_Status; function Info_Log (Subject : Shader) return String is Log_Length : Size := 0; begin API.Get_Shader_Param (Subject.Reference.GL_Id, Enums.Info_Log_Length, Log_Length); -- Returned length includes null termination character Log_Length := Log_Length - 1; declare Info_Log : String (1 .. Integer (Log_Length)); pragma Warnings (Off, Info_Log); C_Info_Log : C.Strings.chars_ptr := C.Strings.New_String (Info_Log); Actual_Length : Size; begin API.Get_Shader_Info_Log (Subject.Reference.GL_Id, Log_Length + 1, Actual_Length, C_Info_Log); if Int (Actual_Length) /= Log_Length then raise Constraint_Error with "Expected info log length of" & Size'Image (Log_Length) & ", actually got" & Size'Image (Actual_Length) & "."; end if; Info_Log := C.Strings.Value (C_Info_Log, C.size_t (Actual_Length)); C.Strings.Free (C_Info_Log); return Info_Log; end; end Info_Log; overriding procedure Initialize_Id (Object : in out Shader) is begin Object.Reference.GL_Id := API.Create_Shader (Object.Kind); Object.Reference.Initialized := True; end Initialize_Id; overriding procedure Delete_Id (Object : in out Shader) is begin API.Delete_Shader (Object.Reference.GL_Id); Object.Reference.GL_Id := 0; Object.Reference.Initialized := False; end Delete_Id; function Create_From_Id (Id : UInt) return Shader is Kind : Shader_Type := Shader_Type'First; begin API.Get_Shader_Type (Id, Enums.Shader_Type, Kind); Raise_Exception_On_OpenGL_Error; return Object : Shader (Kind) do Object.Reference.GL_Id := Id; Object.Reference.Initialized := True; end return; end Create_From_Id; end GL.Objects.Shaders;
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Strings; with GL.API; with GL.Enums; package body GL.Objects.Shaders is procedure Set_Source (Subject : Shader; Source : String) is C_Shader_Source : C.Strings.chars_ptr := C.Strings.New_String (Source); C_Source : constant Low_Level.CharPtr_Array := (1 => C_Shader_Source); Lengths : constant Low_Level.Int_Array := (1 => Source'Length); begin API.Shader_Source (Subject.Reference.GL_Id, 1, C_Source, Lengths); C.Strings.Free (C_Shader_Source); Raise_Exception_On_OpenGL_Error; end Set_Source; function Source (Subject : Shader) return String is Source_Length : Size := 0; begin API.Get_Shader_Param (Subject.Reference.GL_Id, Enums.Shader_Source_Length, Source_Length); declare Shader_Source : String (1 .. Integer (Source_Length)); -- Do not care that we do not assign a value. pragma Warnings (Off, Shader_Source); C_Shader_Source : C.Strings.chars_ptr := C.Strings.New_String (Shader_Source); Actual_Length : Size; begin API.Get_Shader_Source (Subject.Reference.GL_Id, Source_Length, Actual_Length, C_Shader_Source); Shader_Source := C.Strings.Value (C_Shader_Source, C.size_t (Actual_Length)); C.Strings.Free (C_Shader_Source); return Shader_Source; end; end Source; procedure Compile (Subject : Shader) is begin API.Compile_Shader (Subject.Reference.GL_Id); Raise_Exception_On_OpenGL_Error; end Compile; procedure Release_Shader_Compiler renames API.Release_Shader_Compiler; function Compile_Status (Subject : Shader) return Boolean is Value : Int := 0; begin API.Get_Shader_Param (Subject.Reference.GL_Id, Enums.Compile_Status, Value); return Value /= 0; end Compile_Status; function Info_Log (Subject : Shader) return String is Log_Length : Size := 0; begin API.Get_Shader_Param (Subject.Reference.GL_Id, Enums.Info_Log_Length, Log_Length); if Log_Length = 0 then return ""; end if; -- Returned length includes null termination character Log_Length := Log_Length - 1; declare Info_Log : String (1 .. Integer (Log_Length)); pragma Warnings (Off, Info_Log); C_Info_Log : C.Strings.chars_ptr := C.Strings.New_String (Info_Log); Actual_Length : Size; begin API.Get_Shader_Info_Log (Subject.Reference.GL_Id, Log_Length + 1, Actual_Length, C_Info_Log); if Int (Actual_Length) /= Log_Length then raise Constraint_Error with "Expected info log length of" & Size'Image (Log_Length) & ", actually got" & Size'Image (Actual_Length) & "."; end if; Info_Log := C.Strings.Value (C_Info_Log, C.size_t (Actual_Length)); C.Strings.Free (C_Info_Log); return Info_Log; end; end Info_Log; overriding procedure Initialize_Id (Object : in out Shader) is begin Object.Reference.GL_Id := API.Create_Shader (Object.Kind); Object.Reference.Initialized := True; end Initialize_Id; overriding procedure Delete_Id (Object : in out Shader) is begin API.Delete_Shader (Object.Reference.GL_Id); Object.Reference.GL_Id := 0; Object.Reference.Initialized := False; end Delete_Id; function Create_From_Id (Id : UInt) return Shader is Kind : Shader_Type := Shader_Type'First; begin API.Get_Shader_Type (Id, Enums.Shader_Type, Kind); Raise_Exception_On_OpenGL_Error; return Object : Shader (Kind) do Object.Reference.GL_Id := Id; Object.Reference.Initialized := True; end return; end Create_From_Id; end GL.Objects.Shaders;
Fix raise Contraint_Error if info log is empty
gl: Fix raise Contraint_Error if info log is empty When no shader info log exists, 0 is returned as length. This produced a Constraint_Error because we substracted 1 from it (null terminator). Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
0aeacae7a6f007c891f0b148c56bb008ddbe374e
awa/plugins/awa-jobs/src/awa-jobs.ads
awa/plugins/awa-jobs/src/awa-jobs.ads
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Events; with Util.Beans.Objects; with Util.Beans.Basic; with ASF.Applications; -- == Introduction == -- The <b>AWA.Jobs</b> plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. -- -- -- == Data Model == -- @include jobs.hbm.xml -- package AWA.Jobs is end AWA.Jobs;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>AWA.Jobs</b> plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. The `Jobs` plugin is intended to help web application -- designers in implementing end to end asynchronous operation. A client schedules a job -- and does not block nor wait for the immediate completion. Instead, the client asks -- periodically or uses other mechanisms to check for the job completion. -- -- === Writing a job === -- A new job type is created by implementing the `Execute` operation of the abstract -- `Job_Type` tagged record. -- -- type Resize_Job is new AWA.Jobs.Job_Type with ...; -- -- The `Execute` procedure must be implemented. It should use the `Get_Parameter` functions -- to retrieve the job parameters and perform the work. While the job is being executed, -- it can save result by using the `Set_Result` operations, save messages by using the -- `Set_Message` operations and report the progress by using `Set_Progress`. -- It may report the job status by using `Set_Status`. -- -- procedure Execute (Job : in out Resize_Job) is -- begin -- Job.Set_Result ("done", "ok"); -- end Execute; -- -- === Registering a job === -- The <b>AWA.Jobs</b> plugin must be able to create the job instance when it is going to -- be executed. For this, a registration package must be instantiated: -- -- package Resize_Def is new AWA.Jobs.Definition (Resize_Job); -- -- === Scheduling a job === -- To schedule a job, declare an instance of the job to execute and set the job specific -- parameters. The job parameters will be saved in the database. As soon as parameters -- are defined, call the `Schedule` procedure to schedule the job in the job queue and -- obtain a job identifier. -- -- Resize : Resize_Job; -- ... -- Resize.Set_Parameter ("file", "image.png"); -- Resize.Set_Parameter ("width", "32"); -- Resize.Set_Parameter ("height, "32"); -- Resize.Schedule; -- -- === Checking for job completion === -- -- -- == Data Model == -- @include jobs.hbm.xml -- package AWA.Jobs is end AWA.Jobs;
Document the new AWA jobs plugin
Document the new AWA jobs plugin
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d7c9652f2d90177ae9493cfbcb65c160f6843528
awa/plugins/awa-jobs/src/awa-jobs-modules.ads
awa/plugins/awa-jobs/src/awa-jobs-modules.ads
----------------------------------------------------------------------- -- awa-jobs-module -- Job 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 Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with ASF.Applications; with AWA.Modules; with AWA.Jobs.Services; with AWA.Events.Models; -- == Job Module == -- The <b>Jobs.Modules</b> is the entry point for the management of asynchronous jobs. -- It maintains a list of job types that can be executed for the application and it -- manages the job dispatchers. package AWA.Jobs.Modules is NAME : constant String := "jobs"; type Job_Module is new AWA.Modules.Module with private; type Job_Module_Access is access all Job_Module'Class; -- Initialize the job module. overriding procedure Initialize (Plugin : in out Job_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the job module instance associated with the current application. function Get_Job_Module return Job_Module_Access; -- Registers the job work procedure represented by <b>Work</b> under the name <b>Name</b>. procedure Register (Plugin : in out Job_Module; Definition : in AWA.Jobs.Services.Job_Factory_Access); -- Find the job work factory registered under the name <b>Name</b>. -- Returns null if there is no such factory. function Find_Factory (Plugin : in Job_Module; Name : in String) return AWA.Jobs.Services.Job_Factory_Access; -- Create an event to schedule the job execution. procedure Create_Event (Event : in out AWA.Events.Models.Message_Ref); private use AWA.Jobs.Services; -- A factory map to create job instances. package Job_Factory_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Job_Factory_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Job_Module is new AWA.Modules.Module with record Factory : Job_Factory_Map.Map; Queue : AWA.Events.Models.Queue_Ref; Message_Type : AWA.Events.Models.Message_Type_Ref; end record; end AWA.Jobs.Modules;
----------------------------------------------------------------------- -- awa-jobs-modules -- Job module -- 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 Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with ASF.Applications; with AWA.Modules; with AWA.Jobs.Services; -- == Job Module == -- The <b>Jobs.Modules</b> is the entry point for the management of asynchronous jobs. -- It maintains a list of job types that can be executed for the application and it -- manages the job dispatchers. package AWA.Jobs.Modules is NAME : constant String := "jobs"; type Job_Module is new AWA.Modules.Module with private; type Job_Module_Access is access all Job_Module'Class; -- Initialize the job module. overriding procedure Initialize (Plugin : in out Job_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the job module instance associated with the current application. function Get_Job_Module return Job_Module_Access; -- Registers the job work procedure represented by `Work` under the name `Name`. procedure Register (Plugin : in out Job_Module; Definition : in AWA.Jobs.Services.Job_Factory_Access); -- Find the job work factory registered under the name `Name`. -- Returns null if there is no such factory. function Find_Factory (Plugin : in Job_Module; Name : in String) return AWA.Jobs.Services.Job_Factory_Access; private use AWA.Jobs.Services; -- A factory map to create job instances. package Job_Factory_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Job_Factory_Access, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Job_Module is new AWA.Modules.Module with record Factory : Job_Factory_Map.Map; end record; end AWA.Jobs.Modules;
Remove the Create_Event procedure as well as unused members in the Job module
Remove the Create_Event procedure as well as unused members in the Job module
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
cf198376e3fb76f02a941cb866b59e30dc5b328d
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural; Total_Alloc : MAT.Types.Target_Size; Total_Free : MAT.Types.Target_Size; Malloc_Count : Natural; Free_Count : Natural; Realloc_Count : Natural; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural; Total_Alloc : MAT.Types.Target_Size; Total_Free : MAT.Types.Target_Size; Malloc_Count : Natural; Free_Count : Natural; Realloc_Count : Natural; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Declare the Stat_Information protected operation
Declare the Stat_Information protected operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a00ae28427dcdfeb10d008023f7fac3318c7f0c6
src/security-contexts.ads
src/security-contexts.ads
----------------------------------------------------------------------- -- 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.Finalization; with Security.Permissions; with Security.Policies; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; Invalid_Policy : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access; pragma Inline_Always (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; -- 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); -- 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); -- 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); -- 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); -- 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); -- 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); -- Set a policy context information represented by <b>Value</b> and associated with -- the <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); -- 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; -- 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; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (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 Security.Permissions.Permission_Index) return Boolean; -- 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; private -- type Permission_Cache is record -- Perm : Security.Permissions.Permission_Type; -- Result : Boolean; -- end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Policies.Policy_Manager_Access := null; Principal : Security.Principal_Access := null; Contexts : Security.Policies.Policy_Context_Array_Access := null; end record; 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.Finalization; with Security.Permissions; with Security.Policies; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable. -- * This instance will be associated with the current thread through a task attribute -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- * The result produced by the security controller is then saved in the local cache. -- -- For example the security context is declared as follows: -- -- Context : Security.Contexts.Security_Context; -- -- A security policy and a principal must be set in the security context. The security policy -- defines the rules that govern the security and the principal identifies the current user. -- -- Context.Set_Context (Policy_Manager, User); -- -- A permission is checked by using the <tt>Has_Permission</tt> operation: -- -- if Security.Contexts.Has_Permission (Perm_Create_Workspace.Permission); -- package Security.Contexts is Invalid_Context : exception; Invalid_Policy : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access; pragma Inline_Always (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; -- 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); -- 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); -- 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); -- 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); -- 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); -- 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); -- Set a policy context information represented by <b>Value</b> and associated with -- the <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); -- 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; -- 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; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (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 Security.Permissions.Permission_Index) return Boolean; -- 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; private -- type Permission_Cache is record -- Perm : Security.Permissions.Permission_Type; -- Result : Boolean; -- end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Policies.Policy_Manager_Access := null; Principal : Security.Principal_Access := null; Contexts : Security.Policies.Policy_Context_Array_Access := null; end record; end Security.Contexts;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
c8cc42308d8f140d9500afb7cd5d71f36e0ae06a
src/ado-drivers.ads
src/ado-drivers.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- 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.Properties; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Initialize the drivers which are available. procedure Initialize; -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers is use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; type Driver_Index is new Natural range 0 .. 4; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. function Get_Config (Name : in String; Default : in String := "") return String; end ADO.Drivers;
Move the Initialize operation in a separate library
Move the Initialize operation in a separate library
Ada
apache-2.0
Letractively/ada-ado
d96334174aac80f3d0ef171aa5a85a3c24789f31
mat/src/frames/mat-frames.adb
mat/src/frames/mat-frames.adb
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Interfaces; use Interfaces; with MAT.Types; use MAT.Types; package body MAT.Frames is procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Destroy (F); end loop; -- Unlink from parent list. if Frame.Parent /= null then F := Frame.Parent.Children; if F = Frame then Frame.Parent.Children := Frame.Next; else while F /= null and F.Next /= Frame loop F := F.Next; end loop; if F = null then raise Program_Error; end if; F.Next := Frame.Next; end if; end if; Free (Frame); end Destroy; -- Release the frame when its reference is no longer necessary. procedure Release (F : in Frame_Ptr) is Current : Frame_Ptr := F; begin -- Scan the fram until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Ptr := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; end Release; -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. procedure Split (F : in out Frame_Ptr; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Ptr := F.Parent.Children; begin -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; end Split; procedure Add_Frame (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; end loop; Result := Child; end Add_Frame; procedure Insert (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Current : Frame_Ptr := F; Child : Frame_Ptr; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current := Child; Lpos := 2; Pos := Pos + 1; Current.Used := Current.Used + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is Child : Frame_Ptr := F.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (F : in Frame_Ptr; Pc : in PC_Table; Result : out Frame_Ptr; Last_Pc : out Natural) is Current : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search: while Pos <= Pc'Last loop declare Addr : Target_Addr := Pc (Pos); Child : Frame_Ptr := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Interfaces; use Interfaces; with MAT.Types; use MAT.Types; package body MAT.Frames is procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Destroy (F); end loop; -- Unlink from parent list. if Frame.Parent /= null then F := Frame.Parent.Children; if F = Frame then Frame.Parent.Children := Frame.Next; else while F /= null and F.Next /= Frame loop F := F.Next; end loop; if F = null then raise Program_Error; end if; F.Next := Frame.Next; end if; end if; Free (Frame); end Destroy; -- ------------------------------ -- Release the frame when its reference is no longer necessary. -- ------------------------------ procedure Release (Frame : in Frame_Type) is Current : Frame_Type := Frame; begin -- Scan the frame until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Type := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; end Release; -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. procedure Split (F : in out Frame_Ptr; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Ptr := F.Parent.Children; begin -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; end Split; procedure Add_Frame (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; end loop; Result := Child; end Add_Frame; procedure Insert (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Current : Frame_Ptr := F; Child : Frame_Ptr; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current := Child; Lpos := 2; Pos := Pos + 1; Current.Used := Current.Used + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is Child : Frame_Ptr := F.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (F : in Frame_Ptr; Pc : in PC_Table; Result : out Frame_Ptr; Last_Pc : out Natural) is Current : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search: while Pos <= Pc'Last loop declare Addr : Target_Addr := Pc (Pos); Child : Frame_Ptr := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
Refactor the Release operation
Refactor the Release operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
eb494ee7b77a24df8f9e41cabcdb1de9cc64851d
mat/src/memory/mat-memory.ads
mat/src/memory/mat-memory.ads
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; private end MAT.Memory;
----------------------------------------------------------------------- -- Memory - Memory slot -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with MAT.Types; with MAT.Frames; with Interfaces; package MAT.Memory is type Allocation is record Size : MAT.Types.Target_Size; Frame : Frames.Frame_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; end record; -- Statistics about memory allocation. type Memory_Info is record Total_Size : MAT.Types.Target_Size := 0; Alloc_Count : Natural := 0; Min_Slot_Size : MAT.Types.Target_Size := 0; Max_Slot_Size : MAT.Types.Target_Size := 0; end record; use type MAT.Types.Target_Addr; package Allocation_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr, Element_Type => Allocation); subtype Allocation_Map is Allocation_Maps.Map; subtype Allocation_Cursor is Allocation_Maps.Cursor; private end MAT.Memory;
Declare the Memory_Info type
Declare the Memory_Info type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
5b1ea4d30bd96bde515875de1ffb2bb477e28297
src/sys/lzma/util-streams-buffered-lzma.adb
src/sys/lzma/util-streams-buffered-lzma.adb
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Check; with Lzma.Container; with Interfaces.C; with Ada.IO_Exceptions; package body Util.Streams.Buffered.Lzma is use type Interfaces.C.size_t; use type Base.lzma_ret; subtype size_t is Interfaces.C.size_t; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Compress_Stream; Output : access Output_Stream'Class; Size : in Positive) is Result : Base.lzma_ret; begin Output_Buffer_Stream (Stream).Initialize (Output, Size); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; Result := Container.lzma_easy_encoder (Stream.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Device_Error with "Cannot initialize compressor"; end if; end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Compress_Stream) is begin Stream.Flush; Output_Buffer_Stream (Stream).Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Last_Pos : Ada.Streams.Stream_Element_Offset; Encoded : Boolean := False; Result : Base.lzma_ret; begin loop if Stream.Stream.avail_in = 0 then Stream.Stream.next_in := Buffer (Buffer'First)'Unrestricted_Access; Stream.Stream.avail_in := size_t (Buffer'Length); Encoded := True; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK or (Stream.Stream.avail_in = 0 and Encoded); end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Compress_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset; Result : Base.lzma_ret; begin Stream.Stream.next_in := null; Stream.Stream.avail_in := 0; loop Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_FINISH); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK; end loop; end Flush; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Compress_Stream) is begin Base.lzma_end (Object.Stream'Unchecked_Access); Output_Buffer_Stream (Object).Finalize; end Finalize; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Decompress_Stream; Input : access Input_Stream'Class; Size : in Positive) is Result : Base.lzma_ret; begin Input_Buffer_Stream (Stream).Initialize (Input, Size); Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_in := 0; Result := Container.lzma_stream_decoder (Stream.Stream'Unchecked_Access, Long_Long_Integer'Last, Container.LZMA_CONCATENATED); if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Device_Error with "Cannot initialize decompressor"; end if; end Initialize; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Read (Stream : in out Decompress_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is use type Base.lzma_action; Result : Base.lzma_ret; begin Stream.Stream.next_out := Into (Into'First)'Unrestricted_Access; Stream.Stream.avail_out := Into'Length; loop if Stream.Stream.avail_in = 0 and not Stream.Is_Eof and Stream.Action = Base.LZMA_RUN then Stream.Fill; if Stream.Write_Pos >= Stream.Read_Pos then Stream.Stream.avail_in := size_t (Stream.Write_Pos - Stream.Read_Pos); Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; else Stream.Stream.avail_in := 0; Stream.Stream.next_in := null; Stream.Action := Base.LZMA_FINISH; end if; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Stream.Action); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (Stream.Stream.avail_out) - 1; return; end if; if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Data_Error with "Decompression error"; end if; end loop; end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Decompress_Stream) is begin Base.lzma_end (Object.Stream'Unchecked_Access); Input_Buffer_Stream (Object).Finalize; end Finalize; end Util.Streams.Buffered.Lzma;
----------------------------------------------------------------------- -- util-streams-buffered-lzma -- LZMA streams -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Lzma.Check; with Lzma.Container; with Interfaces.C; with Ada.IO_Exceptions; package body Util.Streams.Buffered.Lzma is use type Interfaces.C.size_t; use type Base.lzma_ret; subtype size_t is Interfaces.C.size_t; subtype Offset is Ada.Streams.Stream_Element_Offset; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Compress_Stream; Output : access Output_Stream'Class; Size : in Positive) is Result : Base.lzma_ret; begin Output_Buffer_Stream (Stream).Initialize (Output, Size); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; Result := Container.lzma_easy_encoder (Stream.Stream'Unchecked_Access, 6, Check.LZMA_CHECK_CRC64); if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Device_Error with "Cannot initialize compressor"; end if; end Initialize; -- ----------------------- -- Close the sink. -- ----------------------- overriding procedure Close (Stream : in out Compress_Stream) is begin Stream.Flush; Output_Buffer_Stream (Stream).Close; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Compress_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Last_Pos : Ada.Streams.Stream_Element_Offset; Encoded : Boolean := False; Result : Base.lzma_ret; begin loop if Stream.Stream.avail_in = 0 then Stream.Stream.next_in := Buffer (Buffer'First)'Unrestricted_Access; Stream.Stream.avail_in := size_t (Buffer'Length); Encoded := True; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_RUN); -- Write the output data when the buffer is full or we reached the end of stream. if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK or (Stream.Stream.avail_in = 0 and Encoded); end loop; end Write; -- ----------------------- -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. -- ----------------------- overriding procedure Flush (Stream : in out Compress_Stream) is Last_Pos : Ada.Streams.Stream_Element_Offset; Result : Base.lzma_ret; begin Stream.Stream.next_in := null; Stream.Stream.avail_in := 0; loop Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Base.LZMA_FINISH); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last_Pos := Stream.Buffer'First + Stream.Buffer'Length - Offset (Stream.Stream.avail_out) - 1; Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos)); Stream.Stream.next_out := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_out := Stream.Buffer'Length; end if; exit when Result /= Base.LZMA_OK; end loop; end Flush; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Compress_Stream) is begin Object.Flush; Output_Buffer_Stream (Object).Finalize; Base.lzma_end (Object.Stream'Unchecked_Access); end Finalize; -- ----------------------- -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. -- ----------------------- overriding procedure Initialize (Stream : in out Decompress_Stream; Input : access Input_Stream'Class; Size : in Positive) is Result : Base.lzma_ret; begin Input_Buffer_Stream (Stream).Initialize (Input, Size); Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; Stream.Stream.avail_in := 0; Result := Container.lzma_stream_decoder (Stream.Stream'Unchecked_Access, Long_Long_Integer'Last, Container.LZMA_CONCATENATED); if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Device_Error with "Cannot initialize decompressor"; end if; end Initialize; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Read (Stream : in out Decompress_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is use type Base.lzma_action; Result : Base.lzma_ret; begin Stream.Stream.next_out := Into (Into'First)'Unrestricted_Access; Stream.Stream.avail_out := Into'Length; loop if Stream.Stream.avail_in = 0 and not Stream.Is_Eof and Stream.Action = Base.LZMA_RUN then Stream.Fill; if Stream.Write_Pos >= Stream.Read_Pos then Stream.Stream.avail_in := size_t (Stream.Write_Pos - Stream.Read_Pos); Stream.Stream.next_in := Stream.Buffer (Stream.Buffer'First)'Unchecked_Access; else Stream.Stream.avail_in := 0; Stream.Stream.next_in := null; Stream.Action := Base.LZMA_FINISH; end if; end if; Result := Base.lzma_code (Stream.Stream'Unchecked_Access, Stream.Action); if Stream.Stream.avail_out = 0 or Result = Base.LZMA_STREAM_END then Last := Into'First + Into'Length - Offset (Stream.Stream.avail_out) - 1; return; end if; if Result /= Base.LZMA_OK then raise Ada.IO_Exceptions.Data_Error with "Decompression error"; end if; end loop; end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Decompress_Stream) is begin Base.lzma_end (Object.Stream'Unchecked_Access); Input_Buffer_Stream (Object).Finalize; end Finalize; end Util.Streams.Buffered.Lzma;
Fix Finalize to flush the LZMA before deleting the object
Fix Finalize to flush the LZMA before deleting the object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
557e267328149df187daf21dd67d76f1cb8c85d4
src/mysql/ado-drivers-connections-mysql.ads
src/mysql/ado-drivers-connections-mysql.ads
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- 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 Mysql.Mysql; use Mysql.Mysql; package ADO.Drivers.Connections.Mysql is type Mysql_Driver is limited private; -- Initialize the Mysql driver. procedure Initialize; private -- Create a new MySQL connection using the configuration parameters. procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : out Database_Connection_Access); type Mysql_Driver is new ADO.Drivers.Connections.Driver with record Id : Natural := 0; end record; -- Deletes the Mysql driver. overriding procedure Finalize (D : in out Mysql_Driver); -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Name : Unbounded_String := Null_Unbounded_String; Server_Name : Unbounded_String := Null_Unbounded_String; Login_Name : Unbounded_String := Null_Unbounded_String; Password : Unbounded_String := Null_Unbounded_String; Server : Mysql_Access := null; Connected : Boolean := False; -- MySQL autocommit flag Autocommit : Boolean := True; 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); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); overriding procedure Finalize (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); end ADO.Drivers.Connections.Mysql;
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 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 Mysql.Mysql; use Mysql.Mysql; package ADO.Drivers.Connections.Mysql is type Mysql_Driver is limited private; -- Initialize the Mysql driver. procedure Initialize; private -- Create a new MySQL connection using the configuration parameters. procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); type Mysql_Driver is new ADO.Drivers.Connections.Driver with record Id : Natural := 0; end record; -- Deletes the Mysql driver. overriding procedure Finalize (D : in out Mysql_Driver); -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Name : Unbounded_String := Null_Unbounded_String; Server_Name : Unbounded_String := Null_Unbounded_String; Login_Name : Unbounded_String := Null_Unbounded_String; Password : Unbounded_String := Null_Unbounded_String; Server : Mysql_Access := null; Connected : Boolean := False; -- MySQL autocommit flag Autocommit : Boolean := True; 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); procedure Execute (Database : in out Database_Connection; SQL : in Query_String); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); overriding procedure Finalize (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); end ADO.Drivers.Connections.Mysql;
Update the Create_Connection procedure
Update the Create_Connection procedure
Ada
apache-2.0
stcarrez/ada-ado
94274136935b02d6feb4196ad148ee7a61f6f2e1
mat/src/events/mat-events-targets.adb
mat/src/events/mat-events-targets.adb
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in MAT.Types.Uint16; Frame : in MAT.Events.Frame_Info) is begin Target.Events.Insert (Event, Frame); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_EVent_Counter; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in MAT.Types.Uint16; Frame : in MAT.Events.Frame_Info) is begin null; end Insert; end Event_Collector; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in MAT.Types.Uint16; Frame : in MAT.Events.Frame_Info) is begin Target.Events.Insert (Event, Frame); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_EVent_Counter; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in MAT.Types.Uint16; Frame : in MAT.Events.Frame_Info) is Info : Target_Event; begin Info.Event := Event; Info.Time := Frame.Time; Info.Thread := Frame.Thread; Events.Insert (Frame.Time, Info); end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.First; begin while Event_Maps.Has_Element (Iter) loop Into.Append (Event_Maps.Element (Iter)); Event_Maps.Next (Iter); end loop; end Get_Events; end Event_Collector; end MAT.Events.Targets;
Implement the Get_Events procedure
Implement the Get_Events procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7e301df9da85401589b61c6a0aaed482f4b5420f
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; if Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Into); end Find; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; if Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Into); end Find; end Memory_Allocator; end MAT.Memory.Targets;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0d7245635b807b6c1d3be9d412a3a91bd2657d72
matp/src/events/mat-events-probes.ads
matp/src/events/mat-events-probes.ads
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames; package MAT.Events.Probes is subtype Probe_Event_Type is MAT.Events.Targets.Probe_Event_Type; ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Probe_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in out Probe_Event_Type) is abstract; ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Get the target events. function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access; -- Read a message from the stream. procedure Read_Message (Reader : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is abstract; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (List : in out Reader_List_Type; Manager : in out Probe_Manager_Type'Class) is abstract; private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Targets.Probe_Index_Type; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Probe_Event_Type; Frames : MAT.Frames.Frame_Type; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames; package MAT.Events.Probes is subtype Probe_Event_Type is MAT.Events.Targets.Probe_Event_Type; ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Probe_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in out Probe_Event_Type) is abstract; -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Probe : in Probe_Type; Id : in MAT.Events.Targets.Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in MAT.Events.Targets.Event_Id_Type); ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Get the target events. function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access; -- Read a message from the stream. procedure Read_Message (Reader : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is abstract; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (List : in out Reader_List_Type; Manager : in out Probe_Manager_Type'Class) is abstract; private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Targets.Probe_Index_Type; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Probe_Event_Type; Frames : MAT.Frames.Frame_Type; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
Declare the Update_Event procedure
Declare the Update_Event procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
90729b3dfdc24130d56e99c318eec080006621b7
src/ado-sessions.ads
src/ado-sessions.ads
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Databases; with ADO.Queries; with ADO.SQL; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; -- == Session == -- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions. -- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types. -- -- @include ado-sessions-factory.ads -- package ADO.Sessions is use ADO.Statements; -- Raised for all errors reported by the database DB_Error : exception; -- Raised if the database connection is not open. NOT_OPEN : exception; NOT_FOUND : exception; NO_DATABASE : exception; -- Raised when the connection URI is invalid. Connection_Error : exception; type Object_Factory is tagged private; -- --------- -- Session -- --------- -- Read-only database connection (or slave connection). -- type Session is tagged private; -- Get the session status. function Get_Status (Database : in Session) return ADO.Databases.Connection_Status; -- Close the session. procedure Close (Database : in out Session); -- Get the database connection. function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class; -- Attach the object to the session. procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class); -- Check if the session contains the object identified by the given key. function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean; -- Remove the object from the session cache. procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in String) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement; -- Create a query statement and initialize the SQL statement with the query definition. function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition); -- --------- -- Master Session -- --------- -- Read-write session. -- type Master_Session is new Session with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Session); -- Commit the current transaction. procedure Commit (Database : in out Master_Session); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Session); -- Allocate an identifier for the table. procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class); -- Flush the objects that were modified. procedure Flush (Database : in out Master_Session); -- Create a delete statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an update statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- Create an insert statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access constant ADO.Schemas.Entities.Entity_Cache; type Object_Factory is tagged record A : Integer; end record; type Object_Factory_Access is access all Object_Factory'Class; -- -- type Session_Proxy is limited record -- Counter : Util.Concurrent.Counters.Counter; -- Session : Session_Record_Access; -- Factory : Object_Factory_Access; -- end record; -- The <b>Session_Record</b> maintains the connection information to the database for -- the duration of the session. It also maintains a cache of application objects -- which is used when session objects are fetched (either through Load or a Find). -- The connection is released and the session record is deleted when the session -- is closed with <b>Close</b>. -- -- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b> -- object that allows to give access to the session record associated with the object. -- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply -- unlinked from the session record. type Session_Record is limited record Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Database : ADO.Databases.Master_Connection; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_Access; end record; type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access := null; end record; overriding procedure Adjust (Object : in out Session); overriding procedure Finalize (Object : in out Session); type Factory_Access is access all ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; end record; procedure Check_Session (Database : in Session'Class; Message : in String := ""); pragma Inline (Check_Session); end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Databases; with ADO.Queries; with ADO.SQL; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; -- == Session == -- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions. -- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types. -- It provides operation to create a database statement that can be executed. -- The <tt>Session</tt> type is used to represent read-only database sessions. It provides -- operations to query the database but it does not allow to update or delete content. -- The <tt>Master_Session</tt> type extends the <tt>Session</tt> type to provide write -- access and it provides operations to get update or delete statements. The differentiation -- between the two sessions is provided for the support of database replications with -- databases such as MySQL. -- -- @include ado-sessions-factory.ads -- package ADO.Sessions is use ADO.Statements; -- Raised for all errors reported by the database DB_Error : exception; -- Raised if the database connection is not open. NOT_OPEN : exception; NOT_FOUND : exception; NO_DATABASE : exception; -- Raised when the connection URI is invalid. Connection_Error : exception; type Object_Factory is tagged private; -- --------- -- Session -- --------- -- Read-only database connection (or slave connection). -- type Session is tagged private; -- Get the session status. function Get_Status (Database : in Session) return ADO.Databases.Connection_Status; -- Close the session. procedure Close (Database : in out Session); -- Get the database connection. function Get_Connection (Database : in Session) return ADO.Databases.Connection'Class; -- Attach the object to the session. procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class); -- Check if the session contains the object identified by the given key. function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean; -- Remove the object from the session cache. procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in String) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement; -- Create a query statement and initialize the SQL statement with the query definition. function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition); -- --------- -- Master Session -- --------- -- Read-write session. -- type Master_Session is new Session with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Session); -- Commit the current transaction. procedure Commit (Database : in out Master_Session); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Session); -- Allocate an identifier for the table. procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class); -- Flush the objects that were modified. procedure Flush (Database : in out Master_Session); -- Create a delete statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an update statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- Create an insert statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access constant ADO.Schemas.Entities.Entity_Cache; type Object_Factory is tagged record A : Integer; end record; type Object_Factory_Access is access all Object_Factory'Class; -- The <b>Session_Record</b> maintains the connection information to the database for -- the duration of the session. It also maintains a cache of application objects -- which is used when session objects are fetched (either through Load or a Find). -- The connection is released and the session record is deleted when the session -- is closed with <b>Close</b>. -- -- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b> -- object that allows to give access to the session record associated with the object. -- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply -- unlinked from the session record. type Session_Record is limited record Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Database : ADO.Databases.Master_Connection; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_Access; end record; type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access := null; end record; overriding procedure Adjust (Object : in out Session); overriding procedure Finalize (Object : in out Session); type Factory_Access is access all ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; end record; procedure Check_Session (Database : in Session'Class; Message : in String := ""); pragma Inline (Check_Session); end ADO.Sessions;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
ff21ad9efb15cb701a44aeb1640f1df1f9db65b2
regtests/util-events-timers-tests.adb
regtests/util-events-timers-tests.adb
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- 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; package body Util.Events.Timers.Tests is use Util.Tests; use type Ada.Real_Time.Time; package Caller is new Util.Test_Caller (Test, "Events.Timers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled", Test_Empty_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Process", Test_Timer_Event'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat", Test_Repeat_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat+Process", Test_Many_Timers'Access); end Add_Tests; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class) is begin Sub.Count := Sub.Count + 1; if Sub.Repeat > 1 then Sub.Repeat := Sub.Repeat - 1; Event.Repeat (Ada.Real_Time.Milliseconds (1)); end if; end Time_Handler; -- ----------------------- -- Test empty timers. -- ----------------------- procedure Test_Empty_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Deadline : Ada.Real_Time.Time; begin T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled"); T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value"); R.Cancel; M.Process (Deadline); T.Assert (Deadline = Ada.Real_Time.Time_Last, "The Process operation returned invalid deadline"); end Test_Empty_Timer; procedure Test_Timer_Event (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); delay until Deadline; M.Process (Deadline); Assert_Equals (T, 1, T.Count, "The timer handler was not called"); end Test_Timer_Event; -- ----------------------- -- Test repeating timers. -- ----------------------- procedure Test_Repeat_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin T.Count := 0; T.Repeat := 5; for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); loop delay until Deadline; M.Process (Deadline); exit when Deadline >= Now + Ada.Real_Time.Seconds (1); end loop; Assert_Equals (T, 5, T.Count, "The timer handler was not repeated"); end Test_Repeat_Timer; -- ----------------------- -- Test executing several timers. -- ----------------------- procedure Test_Many_Timers (T : in out Test) is Timer_Count : constant Positive := 30; type Timer_Ref_Array is array (1 .. Timer_Count) of Timer_Ref; type Test_Ref_Array is array (1 .. Timer_Count) of aliased Test; M : Timer_List; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; R : Timer_Ref_Array; D : Test_Ref_Array; Dt : Ada.Real_Time.Time_Span; Count : Natural := 0; begin for I in R'Range loop D (I).Count := 0; D (I).Repeat := 4; if I mod 2 = 0 then Dt := Ada.Real_Time.Milliseconds (40); else Dt := Ada.Real_Time.Milliseconds (20); end if; M.Set_Timer (D (I)'Unchecked_Access, R (I), Start + Dt); end loop; loop M.Process (Deadline); exit when Deadline >= Start + Ada.Real_Time.Seconds (10); Count := Count + 1; delay until Deadline; end loop; Util.Tests.Assert_Equals (T, 4, Count, "Count of Process"); for I in D'Range loop Util.Tests.Assert_Equals (T, 4, D (I).Count, "Invalid count for timer at " & Natural'Image (I) & " " & Natural'Image (Count)); end loop; end Test_Many_Timers; end Util.Events.Timers.Tests;
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- 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; package body Util.Events.Timers.Tests is use Util.Tests; use type Ada.Real_Time.Time; package Caller is new Util.Test_Caller (Test, "Events.Timers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Events.Timers.Is_Scheduled", Test_Empty_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Process", Test_Timer_Event'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat", Test_Repeat_Timer'Access); Caller.Add_Test (Suite, "Test Util.Events.Timers.Repeat+Process", Test_Many_Timers'Access); end Add_Tests; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class) is begin Sub.Count := Sub.Count + 1; if Sub.Repeat > 1 then Sub.Repeat := Sub.Repeat - 1; Event.Repeat (Ada.Real_Time.Milliseconds (1)); end if; end Time_Handler; -- ----------------------- -- Test empty timers. -- ----------------------- procedure Test_Empty_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Deadline : Ada.Real_Time.Time; begin T.Assert (not R.Is_Scheduled, "Empty timer should not be scheduled"); T.Assert (R.Time_Of_Event = Ada.Real_Time.Time_Last, "Time_Of_Event returned invalid value"); R.Cancel; M.Process (Deadline); T.Assert (Deadline = Ada.Real_Time.Time_Last, "The Process operation returned invalid deadline"); end Test_Empty_Timer; procedure Test_Timer_Event (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); delay until Deadline; M.Process (Deadline); Assert_Equals (T, 1, T.Count, "The timer handler was not called"); end Test_Timer_Event; -- ----------------------- -- Test repeating timers. -- ----------------------- procedure Test_Repeat_Timer (T : in out Test) is M : Timer_List; R : Timer_Ref; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; Now : Ada.Real_Time.Time; begin T.Count := 0; T.Repeat := 5; for Retry in 1 .. 10 loop M.Set_Timer (T'Unchecked_Access, R, Start + Ada.Real_Time.Milliseconds (10)); M.Process (Deadline); Now := Ada.Real_Time.Clock; exit when Now < Deadline; end loop; T.Assert (Now < Deadline, "The timer deadline is not correct"); loop delay until Deadline; M.Process (Deadline); exit when Deadline >= Now + Ada.Real_Time.Seconds (1); end loop; Assert_Equals (T, 5, T.Count, "The timer handler was not repeated"); end Test_Repeat_Timer; -- ----------------------- -- Test executing several timers. -- ----------------------- procedure Test_Many_Timers (T : in out Test) is Timer_Count : constant Positive := 30; type Timer_Ref_Array is array (1 .. Timer_Count) of Timer_Ref; type Test_Ref_Array is array (1 .. Timer_Count) of aliased Test; M : Timer_List; Start : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Deadline : Ada.Real_Time.Time; R : Timer_Ref_Array; D : Test_Ref_Array; Dt : Ada.Real_Time.Time_Span; Count : Natural := 0; begin for I in R'Range loop D (I).Count := 0; D (I).Repeat := 4; if I mod 2 = 0 then Dt := Ada.Real_Time.Milliseconds (40); else Dt := Ada.Real_Time.Milliseconds (20); end if; M.Set_Timer (D (I)'Unchecked_Access, R (I), Start + Dt); end loop; loop M.Process (Deadline); exit when Deadline >= Start + Ada.Real_Time.Seconds (10); Count := Count + 1; delay until Deadline; end loop; Util.Tests.Assert_Equals (T, 8, Count, "Count of Process"); for I in D'Range loop Util.Tests.Assert_Equals (T, 4, D (I).Count, "Invalid count for timer at " & Natural'Image (I) & " " & Natural'Image (Count)); end loop; end Test_Many_Timers; end Util.Events.Timers.Tests;
Fix the timer unit test
Fix the timer unit test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9485cfa92c54577b13a590a2f4fbac170f5b0aab
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Add F_FILE_NAME, F_FUNCTION_NAME and F_LINE_NUMBER
Add F_FILE_NAME, F_FUNCTION_NAME and F_LINE_NUMBER
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ad3a6cf387c0c9d0e629cfa80482aa34f0612802
regtests/asf-converters-tests.adb
regtests/asf-converters-tests.adb
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Calendar.Formatting; with Ada.Unchecked_Deallocation; with Util.Beans.Objects.Time; with Util.Test_Caller; with Util.Dates; with ASF.Tests; with ASF.Components.Html.Text; with ASF.Converters.Dates; package body ASF.Converters.Tests is use Util.Tests; use ASF.Converters.Dates; package Caller is new Util.Test_Caller (Test, "Converters"); procedure Test_Date_Conversion (T : in out Test; Date_Style : in Dates.Style_Type; Time_Style : in Dates.Style_Type; Expect : in String); procedure Test_Conversion_Error (T : in out Test; Value : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Short)", Test_Date_Short_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Medium)", Test_Date_Medium_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Long)", Test_Date_Long_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Full)", Test_Date_Full_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Short)", Test_Time_Short_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Medium)", Test_Time_Medium_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Long)", Test_Time_Long_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_Object (Error)", Test_Date_Converter_Error'Access); end Add_Tests; -- ------------------------------ -- Test getting an attribute from the faces context. -- ------------------------------ procedure Test_Date_Conversion (T : in out Test; Date_Style : in Dates.Style_Type; Time_Style : in Dates.Style_Type; Expect : in String) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class, Name => ASF.Converters.Dates.Date_Converter_Access); Ctx : aliased ASF.Contexts.Faces.Faces_Context; UI : ASF.Components.Html.Text.UIOutput; C : ASF.Converters.Dates.Date_Converter_Access; D : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 3, 4, 5); begin T.Setup (Ctx); ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, ASF.Tests.Get_Application.all'Access); if Date_Style = Dates.DEFAULT then C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.TIME, Locale => "en", Pattern => ""); elsif Time_Style = Dates.DEFAULT then C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.DATE, Locale => "en", Pattern => ""); else C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.BOTH, Locale => "en", Pattern => ""); end if; UI.Set_Converter (C.all'Access); declare use type Ada.Calendar.Time; R : constant String := C.To_String (Ctx, UI, Util.Beans.Objects.Time.To_Object (D)); V : Util.Beans.Objects.Object; S : Util.Dates.Date_Record; begin Util.Tests.Assert_Equals (T, Expect, R, "Invalid date conversion"); V := C.To_Object (Ctx, UI, R); Util.Dates.Split (Into => S, Date => Util.Beans.Objects.Time.To_Time (V)); if Date_Style /= Dates.DEFAULT then T.Assert (Util.Dates.Is_Same_Day (Util.Beans.Objects.Time.To_Time (V), D), "Invalid date"); else Util.Tests.Assert_Equals (T, 3, Natural (S.Hour), "Invalid date conversion: hour"); Util.Tests.Assert_Equals (T, 4, Natural (S.Minute), "Invalid date conversion: minute"); if Time_Style = Dates.LONG then Util.Tests.Assert_Equals (T, 5, Natural (S.Second), "Invalid date conversion: second"); end if; end if; exception when others => T.Fail ("Exception when converting date string: " & R); end; Free (C); end Test_Date_Conversion; -- ------------------------------ -- Test the date short converter. -- ------------------------------ procedure Test_Date_Short_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.SHORT, ASF.Converters.Dates.DEFAULT, "19/11/2011"); end Test_Date_Short_Converter; -- ------------------------------ -- Test the date medium converter. -- ------------------------------ procedure Test_Date_Medium_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.MEDIUM, ASF.Converters.Dates.DEFAULT, "Nov 19, 2011"); end Test_Date_Medium_Converter; -- ------------------------------ -- Test the date long converter. -- ------------------------------ procedure Test_Date_Long_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.LONG, ASF.Converters.Dates.DEFAULT, "November 19, 2011"); end Test_Date_Long_Converter; -- ------------------------------ -- Test the date full converter. -- ------------------------------ procedure Test_Date_Full_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.FULL, ASF.Converters.Dates.DEFAULT, "Saturday, November 19, 2011"); end Test_Date_Full_Converter; -- ------------------------------ -- Test the time short converter. -- ------------------------------ procedure Test_Time_Short_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.SHORT, "03:04"); end Test_Time_Short_Converter; -- ------------------------------ -- Test the time short converter. -- ------------------------------ procedure Test_Time_Medium_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.MEDIUM, "03:04"); end Test_Time_Medium_Converter; -- ------------------------------ -- Test the time long converter. -- ------------------------------ procedure Test_Time_Long_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.LONG, "03:04:05"); end Test_Time_Long_Converter; -- ------------------------------ -- Test getting an attribute from the faces context. -- ------------------------------ procedure Test_Conversion_Error (T : in out Test; Value : in String) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class, Name => ASF.Converters.Dates.Date_Converter_Access); Ctx : aliased ASF.Contexts.Faces.Faces_Context; UI : ASF.Components.Html.Text.UIOutput; C : ASF.Converters.Dates.Date_Converter_Access; begin T.Setup (Ctx); ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, ASF.Tests.Get_Application.all'Access); C := ASF.Converters.Dates.Create_Date_Converter (Date => ASF.Converters.Dates.LONG, Time => ASF.Converters.Dates.LONG, Format => ASF.Converters.Dates.BOTH, Locale => "en", Pattern => ""); UI.Set_Converter (C.all'Access); declare V : Util.Beans.Objects.Object; pragma Unreferenced (V); begin V := C.To_Object (Ctx, UI, Value); T.Fail ("No exception raised for " & Value); exception when Invalid_Conversion => null; end; Free (C); end Test_Conversion_Error; -- ------------------------------ -- Test converter reporting conversion errors when converting a string back to a date. -- ------------------------------ procedure Test_Date_Converter_Error (T : in out Test) is begin Test_Conversion_Error (T, "some invalid date"); end Test_Date_Converter_Error; end ASF.Converters.Tests;
----------------------------------------------------------------------- -- Faces Context Tests - Unit tests for ASF.Contexts.Faces -- Copyright (C) 2010, 2011, 2012, 2013, 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.Calendar; with Ada.Calendar.Formatting; with Ada.Unchecked_Deallocation; with Util.Beans.Objects.Time; with Util.Test_Caller; with Util.Dates; with ASF.Tests; with ASF.Components.Html.Text; with ASF.Converters.Dates; with ASF.Converters.Numbers; package body ASF.Converters.Tests is use Util.Tests; use ASF.Converters.Dates; package Caller is new Util.Test_Caller (Test, "Converters"); procedure Test_Date_Conversion (T : in out Test; Date_Style : in Dates.Style_Type; Time_Style : in Dates.Style_Type; Expect : in String); procedure Test_Conversion_Error (T : in out Test; Value : in String); procedure Test_Number_Conversion (T : in out Test; Picture : in String; Value : in Float; Expect : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- To document what is tested, register the test methods for each -- operation that is tested. Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Short)", Test_Date_Short_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Medium)", Test_Date_Medium_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Long)", Test_Date_Long_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Date, Full)", Test_Date_Full_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Short)", Test_Time_Short_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Medium)", Test_Time_Medium_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_String (Time, Long)", Test_Time_Long_Converter'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Dates.To_Object (Error)", Test_Date_Converter_Error'Access); Caller.Add_Test (Suite, "Test ASF.Converters.Numbers.To_String (Float)", Test_Number_Converter'Access); end Add_Tests; -- ------------------------------ -- Test getting an attribute from the faces context. -- ------------------------------ procedure Test_Date_Conversion (T : in out Test; Date_Style : in Dates.Style_Type; Time_Style : in Dates.Style_Type; Expect : in String) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class, Name => ASF.Converters.Dates.Date_Converter_Access); Ctx : aliased ASF.Contexts.Faces.Faces_Context; UI : ASF.Components.Html.Text.UIOutput; C : ASF.Converters.Dates.Date_Converter_Access; D : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 3, 4, 5); begin T.Setup (Ctx); ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, ASF.Tests.Get_Application.all'Access); if Date_Style = Dates.DEFAULT then C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.TIME, Locale => "en", Pattern => ""); elsif Time_Style = Dates.DEFAULT then C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.DATE, Locale => "en", Pattern => ""); else C := ASF.Converters.Dates.Create_Date_Converter (Date => Date_Style, Time => Time_Style, Format => ASF.Converters.Dates.BOTH, Locale => "en", Pattern => ""); end if; UI.Set_Converter (C.all'Access); declare use type Ada.Calendar.Time; R : constant String := C.To_String (Ctx, UI, Util.Beans.Objects.Time.To_Object (D)); V : Util.Beans.Objects.Object; S : Util.Dates.Date_Record; begin Util.Tests.Assert_Equals (T, Expect, R, "Invalid date conversion"); V := C.To_Object (Ctx, UI, R); Util.Dates.Split (Into => S, Date => Util.Beans.Objects.Time.To_Time (V)); if Date_Style /= Dates.DEFAULT then T.Assert (Util.Dates.Is_Same_Day (Util.Beans.Objects.Time.To_Time (V), D), "Invalid date"); else Util.Tests.Assert_Equals (T, 3, Natural (S.Hour), "Invalid date conversion: hour"); Util.Tests.Assert_Equals (T, 4, Natural (S.Minute), "Invalid date conversion: minute"); if Time_Style = Dates.LONG then Util.Tests.Assert_Equals (T, 5, Natural (S.Second), "Invalid date conversion: second"); end if; end if; exception when others => T.Fail ("Exception when converting date string: " & R); end; Free (C); end Test_Date_Conversion; -- ------------------------------ -- Test the date short converter. -- ------------------------------ procedure Test_Date_Short_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.SHORT, ASF.Converters.Dates.DEFAULT, "19/11/2011"); end Test_Date_Short_Converter; -- ------------------------------ -- Test the date medium converter. -- ------------------------------ procedure Test_Date_Medium_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.MEDIUM, ASF.Converters.Dates.DEFAULT, "Nov 19, 2011"); end Test_Date_Medium_Converter; -- ------------------------------ -- Test the date long converter. -- ------------------------------ procedure Test_Date_Long_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.LONG, ASF.Converters.Dates.DEFAULT, "November 19, 2011"); end Test_Date_Long_Converter; -- ------------------------------ -- Test the date full converter. -- ------------------------------ procedure Test_Date_Full_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.FULL, ASF.Converters.Dates.DEFAULT, "Saturday, November 19, 2011"); end Test_Date_Full_Converter; -- ------------------------------ -- Test the time short converter. -- ------------------------------ procedure Test_Time_Short_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.SHORT, "03:04"); end Test_Time_Short_Converter; -- ------------------------------ -- Test the time short converter. -- ------------------------------ procedure Test_Time_Medium_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.MEDIUM, "03:04"); end Test_Time_Medium_Converter; -- ------------------------------ -- Test the time long converter. -- ------------------------------ procedure Test_Time_Long_Converter (T : in out Test) is begin Test_Date_Conversion (T, ASF.Converters.Dates.DEFAULT, ASF.Converters.Dates.LONG, "03:04:05"); end Test_Time_Long_Converter; -- ------------------------------ -- Test getting an attribute from the faces context. -- ------------------------------ procedure Test_Conversion_Error (T : in out Test; Value : in String) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Dates.Date_Converter'Class, Name => ASF.Converters.Dates.Date_Converter_Access); Ctx : aliased ASF.Contexts.Faces.Faces_Context; UI : ASF.Components.Html.Text.UIOutput; C : ASF.Converters.Dates.Date_Converter_Access; begin T.Setup (Ctx); ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, ASF.Tests.Get_Application.all'Access); C := ASF.Converters.Dates.Create_Date_Converter (Date => ASF.Converters.Dates.LONG, Time => ASF.Converters.Dates.LONG, Format => ASF.Converters.Dates.BOTH, Locale => "en", Pattern => ""); UI.Set_Converter (C.all'Access); declare V : Util.Beans.Objects.Object; pragma Unreferenced (V); begin V := C.To_Object (Ctx, UI, Value); T.Fail ("No exception raised for " & Value); exception when Invalid_Conversion => null; end; Free (C); end Test_Conversion_Error; -- ------------------------------ -- Test converter reporting conversion errors when converting a string back to a date. -- ------------------------------ procedure Test_Date_Converter_Error (T : in out Test) is begin Test_Conversion_Error (T, "some invalid date"); end Test_Date_Converter_Error; -- Test number converter. procedure Test_Number_Conversion (T : in out Test; Picture : in String; Value : in Float; Expect : in String) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Numbers.Number_Converter'Class, Name => ASF.Converters.Numbers.Number_Converter_Access); Ctx : aliased ASF.Contexts.Faces.Faces_Context; UI : ASF.Components.Html.Text.UIOutput; C : ASF.Converters.Numbers.Number_Converter_Access; D : Util.Beans.Objects.Object := Util.Beans.Objects.To_Object (Value); begin T.Setup (Ctx); ASF.Contexts.Faces.Set_Current (Ctx'Unchecked_Access, ASF.Tests.Get_Application.all'Access); C := new ASF.Converters.Numbers.Number_Converter; UI.Set_Converter (C.all'Access); C.Set_Picture (Picture); declare use type Ada.Calendar.Time; R : constant String := C.To_String (Ctx, UI, D); begin Util.Tests.Assert_Equals (T, Expect, R, "Invalid number conversion with picture " & Picture); end; Free (C); end Test_Number_Conversion; -- ------------------------------ -- Test converter reporting conversion errors when converting a string back to a date. -- ------------------------------ procedure Test_Number_Converter (T : in out Test) is begin Test_Number_Conversion (T, "Z9.99", 12.345323, "12.35"); Test_Number_Conversion (T, "Z9.99", 2.334323, " 2.33"); Test_Number_Conversion (T, "<$Z_ZZ9.99>", 2.334323, " € 2.33 "); Test_Number_Conversion (T, "Z_ZZ9.99B$", 2.334323, " 2.33 €"); Test_Number_Conversion (T, "Z_ZZ9.99B$", 2342.334323, "2,342.33 €"); Test_Number_Conversion (T, "Z_ZZ9.99B$", 21342.334323, "2,342.33 €"); end Test_Number_Converter; end ASF.Converters.Tests;
Add Test_Number_Converter and register the new test
Add Test_Number_Converter and register the new test
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
e5238852b85f93a077e2be653d43b6cf529af6bb
regtests/util-streams-texts-tests.adb
regtests/util-streams-texts-tests.adb
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2012, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; package body Util.Streams.Texts.Tests is use Ada.Streams.Stream_IO; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Streams.Texts"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close", Test_Read_Line'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Integer)", Test_Write_Integer'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Long_Long_Integer)", Test_Write_Long_Integer'Access); end Add_Tests; -- ------------------------------ -- Test reading a text stream. -- ------------------------------ procedure Test_Read_Line (T : in out Test) is Stream : aliased Files.File_Stream; Reader : Util.Streams.Texts.Reader_Stream; Count : Natural := 0; begin Stream.Open (Name => "Makefile", Mode => In_File); Reader.Initialize (From => Stream'Access); while not Reader.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Reader.Read_Line (Line); Count := Count + 1; end; end loop; Stream.Close; T.Assert (Count > 100, "Too few lines read"); end Test_Read_Line; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write_Integer (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); -- Write '0' (we don't want the Ada spurious space). Stream.Write (Integer (0)); Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '1234' Stream.Write (Integer (1234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "1234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '-234' Stream.Write (Integer (-234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "-234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write_Integer; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write_Long_Integer (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 64); -- Write '0' (we don't want the Ada spurious space). Stream.Write (Long_Long_Integer (0)); Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '1234' Stream.Write (Long_Long_Integer (123456789012345)); Assert_Equals (T, 15, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 15, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "123456789012345", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '-2345678901234' Stream.Write (Long_Long_Integer (-2345678901234)); Assert_Equals (T, 14, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 14, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "-2345678901234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write_Long_Integer; end Util.Streams.Texts.Tests;
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2012, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; package body Util.Streams.Texts.Tests is use Ada.Streams.Stream_IO; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Streams.Texts"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close", Test_Read_Line'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Integer)", Test_Write_Integer'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Long_Long_Integer)", Test_Write_Long_Integer'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Unbounded_String)", Test_Write'Access); end Add_Tests; -- ------------------------------ -- Test reading a text stream. -- ------------------------------ procedure Test_Read_Line (T : in out Test) is Stream : aliased Files.File_Stream; Reader : Util.Streams.Texts.Reader_Stream; Count : Natural := 0; begin Stream.Open (Name => "Makefile", Mode => In_File); Reader.Initialize (From => Stream'Access); while not Reader.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Reader.Read_Line (Line); Count := Count + 1; end; end loop; Stream.Close; T.Assert (Count > 100, "Too few lines read"); end Test_Read_Line; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write_Integer (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); -- Write '0' (we don't want the Ada spurious space). Stream.Write (Integer (0)); Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '1234' Stream.Write (Integer (1234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "1234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '-234' Stream.Write (Integer (-234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "-234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write_Integer; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write_Long_Integer (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 64); -- Write '0' (we don't want the Ada spurious space). Stream.Write (Long_Long_Integer (0)); Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '1234' Stream.Write (Long_Long_Integer (123456789012345)); Assert_Equals (T, 15, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 15, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "123456789012345", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '-2345678901234' Stream.Write (Long_Long_Integer (-2345678901234)); Assert_Equals (T, 14, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 14, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "-2345678901234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write_Long_Integer; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write (T : in out Test) is use Ada.Strings.Unbounded; Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 10); Stream.Write (Ada.Strings.Unbounded.To_Unbounded_String ("hello")); Assert_Equals (T, 5, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 5, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "hello", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Wide string Stream.Write (Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String ("hello")); Assert_Equals (T, 5, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 5, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "hello", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write; end Util.Streams.Texts.Tests;
Implement the Test_Write procedure and register it for execution
Implement the Test_Write procedure and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
cfc0936ab9732d8fc93e5ab1da5f438b45a7bdf9
regtests/ado-audits-tests.adb
regtests/ado-audits-tests.adb
----------------------------------------------------------------------- -- ado-audits-tests -- Audit tests -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with Ada.Text_IO; with Regtests.Audits.Model; with ADO.SQL; with ADO.Sessions.Entities; package body ADO.Audits.Tests is use type ADO.Objects.Object_Key_Type; package Caller is new Util.Test_Caller (Test, "ADO.Audits"); type Test_Audit_Manager is new Audit_Manager with null record; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array); Audit_Instance : aliased Test_Audit_Manager; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array) is pragma Unreferenced (Manager); Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key); begin for C of Changes loop declare Audit : Regtests.Audits.Model.Audit_Ref; begin if Object.Key_Type = ADO.Objects.KEY_INTEGER then Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key)); end if; Audit.Set_Entity_Type (Kind); Audit.Set_Old_Value (UBO.To_String (C.Old_Value)); Audit.Set_New_Value (UBO.To_String (C.New_Value)); Audit.Set_Date (Now); Audit.Save (Session); end; end loop; end Save; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field", Test_Audit_Field'Access); end Add_Tests; procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin Regtests.Set_Audit_Manager (Audit_Instance'Access); end Set_Up; -- ------------------------------ -- Test populating Audit_Fields -- ------------------------------ procedure Test_Audit_Field (T : in out Test) is type Identifier_Array is array (1 .. 10) of ADO.Identifier; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Email : Regtests.Audits.Model.Email_Ref; Prop : Regtests.Audits.Model.Property_Ref; List : Identifier_Array; begin for I in List'Range loop Email := Regtests.Audits.Model.Null_Email; Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com"); Email.Set_Status (ADO.Nullable_Integer '(23, False)); Email.Save (DB); List (I) := Email.Get_Id; end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@here.com"); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@there.com"); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Null_Integer); Email.Save (DB); end loop; DB.Commit; Prop.set_Id (Util.Tests.Get_Uuid); for I in 1 .. 10 loop Prop.Set_Value ((Value => I, Is_Null => False)); Prop.Set_Float_Value (3.0 * Float (I)); Prop.Save (DB); end loop; declare Query : ADO.SQL.Query; Audit_List : Regtests.Audits.Model.Audit_Vector; begin Query.Set_Filter ("entity_id = :entity_id"); for Id of List loop Query.Bind_Param ("entity_id", Id); Regtests.Audits.Model.List (Audit_List, DB, Query); for A of Audit_List loop Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " " & ADO.Identifier'Image (A.Get_Id) & " " & A.Get_Old_Value & " - " & A.Get_New_Value); Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id), "Invalid audit record: id is wrong"); end loop; Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length), "Invalid number of audit records"); end loop; end; end Test_Audit_Field; end ADO.Audits.Tests;
----------------------------------------------------------------------- -- ado-audits-tests -- Audit tests -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with Ada.Text_IO; with Regtests.Audits.Model; with ADO.SQL; with ADO.Sessions.Entities; package body ADO.Audits.Tests is use type ADO.Objects.Object_Key_Type; package Caller is new Util.Test_Caller (Test, "ADO.Audits"); type Test_Audit_Manager is new Audit_Manager with null record; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array); Audit_Instance : aliased Test_Audit_Manager; -- Save the audit changes in the database. overriding procedure Save (Manager : in out Test_Audit_Manager; Session : in out ADO.Sessions.Master_Session'Class; Object : in Auditable_Object_Record'Class; Changes : in Audit_Array) is pragma Unreferenced (Manager); Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key); begin for C of Changes loop declare Audit : Regtests.Audits.Model.Audit_Ref; begin if Object.Key_Type = ADO.Objects.KEY_INTEGER then Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key)); end if; Audit.Set_Entity_Type (Kind); Audit.Set_Old_Value (UBO.To_String (C.Old_Value)); Audit.Set_New_Value (UBO.To_String (C.New_Value)); Audit.Set_Date (Now); Audit.Save (Session); end; end loop; end Save; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field", Test_Audit_Field'Access); end Add_Tests; procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin Regtests.Set_Audit_Manager (Audit_Instance'Access); end Set_Up; -- ------------------------------ -- Test populating Audit_Fields -- ------------------------------ procedure Test_Audit_Field (T : in out Test) is type Identifier_Array is array (1 .. 10) of ADO.Identifier; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Email : Regtests.Audits.Model.Email_Ref; Prop : Regtests.Audits.Model.Property_Ref; List : Identifier_Array; begin for I in List'Range loop Email := Regtests.Audits.Model.Null_Email; Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com"); Email.Set_Status (ADO.Nullable_Integer '(23, False)); Email.Save (DB); List (I) := Email.Get_Id; end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Natural (Id)) & Util.Strings.Image (Email.Get_Status.Value) & "@here.com"); Email.Save (DB); Email.Set_Email ("Email" & Util.Strings.Image (Natural (Id)) & Util.Strings.Image (Email.Get_Status.Value) & "@there.com"); Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False)); Email.Save (DB); end loop; DB.Commit; for Id of List loop Email.Load (DB, Id); Email.Set_Status (ADO.Null_Integer); Email.Save (DB); end loop; DB.Commit; Prop.set_Id (Util.Tests.Get_Uuid); for I in 1 .. 10 loop Prop.Set_Value ((Value => I, Is_Null => False)); Prop.Set_Float_Value (3.0 * Float (I)); Prop.Save (DB); end loop; declare Query : ADO.SQL.Query; Audit_List : Regtests.Audits.Model.Audit_Vector; begin Query.Set_Filter ("entity_id = :entity_id"); for Id of List loop Query.Bind_Param ("entity_id", Id); Regtests.Audits.Model.List (Audit_List, DB, Query); for A of Audit_List loop Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " " & ADO.Identifier'Image (A.Get_Id) & " " & A.Get_Old_Value & " - " & A.Get_New_Value); Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id), "Invalid audit record: id is wrong"); end loop; Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length), "Invalid number of audit records"); end loop; end; end Test_Audit_Field; end ADO.Audits.Tests;
Fix the unit test to make sure the test email address is unique
Fix the unit test to make sure the test email address is unique
Ada
apache-2.0
stcarrez/ada-ado
bc24f498e5d5d5659b5d26a7ddb56092c7893320
regtests/asf-routes-tests.adb
regtests/asf-routes-tests.adb
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Measures; with Util.Log.Loggers; with Util.Test_Caller; with EL.Contexts.Default; package body ASF.Routes.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests"); package Caller is new Util.Test_Caller (Test, "Routes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)", Test_Add_Route_With_Path'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)", Test_Add_Route_With_Param'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)", Test_Add_Route_With_Ext'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)", Test_Add_Route_With_EL'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Iterate", Test_Iterate'Access); end Add_Tests; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return Util.Beans.Objects.To_Object (Bean.Id); elsif Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is begin T.Bean := new Test_Bean; ASF.Tests.EL_Test (T).Set_Up; T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"), Util.Beans.Objects.To_Object (T.Bean.all'Access)); for I in T.Routes'Range loop T.Routes (I) := Route_Type_Refs.Create (new Test_Route_Type '(Util.Refs.Ref_Entity with Index => I)); end loop; end Set_Up; -- ------------------------------ -- Verify that the path matches the given route. -- ------------------------------ procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).Value; R : Route_Context_Type; begin Router.Find_Route (Path, R); declare P : constant String := Get_Path (R); begin T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path); T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path); T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path); -- Inject the path parameters in the bean instance. Inject_Parameters (R, Bean, T.ELContext.all); end; end Verify_Route; -- ------------------------------ -- Add the route associted with the path pattern. -- ------------------------------ procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).Value; begin Router.Add_Route (Path, Route, T.ELContext.all); Verify_Route (T, Router, Path, Index, Bean); end Add_Route; -- ------------------------------ -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html -- ------------------------------ procedure Test_Add_Route_With_Path (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/page.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); Verify_Route (T, Router, "/list/index.html", 3, Bean); end Test_Add_Route_With_Path; -- ------------------------------ -- Test the Add_Route with extension mapping. -- Example: /list/*.html -- ------------------------------ procedure Test_Add_Route_With_Ext (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/*.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean); Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean); Add_Route (T, Router, "/view/page/content/*.html", 6, Bean); Add_Route (T, Router, "/ajax/*", 7, Bean); Add_Route (T, Router, "*.html", 8, Bean); -- Verify precedence and wildcard matching. Verify_Route (T, Router, "/list/index.html", 3, Bean); Verify_Route (T, Router, "/list/admin.html", 2, Bean); Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean); Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean); Verify_Route (T, Router, "/ajax/form/save", 7, Bean); Verify_Route (T, Router, "/view/index.html", 8, Bean); end Test_Add_Route_With_Ext; -- ------------------------------ -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html -- ------------------------------ procedure Test_Add_Route_With_Param (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/users/:id/view.html", 1, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/list.html", 2, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/index.html", 3, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path"); Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name"); Add_Route (T, Router, "/users/list/index.html", 8, Bean); Verify_Route (T, Router, "/users/1234/view.html", 1, Bean); T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id"); Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean); T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_Param; -- ------------------------------ -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html -- ------------------------------ procedure Test_Add_Route_With_EL (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : aliased Test_Bean; begin Add_Route (T, Router, "/users/#{user.id}", 1, Bean); Add_Route (T, Router, "/users/view.html", 2, Bean); Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean); Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean); -- Verify that the path parameters are injected in the 'user' bean (= T.Bean). Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean); T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_EL; P_1 : aliased constant String := "/list/index.html"; P_2 : aliased constant String := "/users/:id"; P_3 : aliased constant String := "/users/:id/view"; P_4 : aliased constant String := "/users/index.html"; P_5 : aliased constant String := "/users/:id/:name"; P_6 : aliased constant String := "/users/:id/:name/view.html"; P_7 : aliased constant String := "/users/:id/list"; P_8 : aliased constant String := "/users/test.html"; P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html"; P_10 : aliased constant String := "/admin/*.html"; P_11 : aliased constant String := "/admin/*.png"; P_12 : aliased constant String := "/admin/*.jpg"; P_13 : aliased constant String := "/users/:id/page/*.xml"; P_14 : aliased constant String := "/*.jsf"; type Const_String_Access is access constant String; type String_Array is array (Positive range <>) of Const_String_Access; Path_Array : constant String_Array := (P_1'Access, P_2'Access, P_3'Access, P_4'Access, P_5'Access, P_6'Access, P_7'Access, P_8'Access, P_9'Access, P_10'Access, P_11'Access, P_12'Access, P_13'Access, P_14'Access); -- ------------------------------ -- Test the Iterate over several paths. -- ------------------------------ procedure Test_Iterate (T : in out Test) is Router : Router_Type; Bean : Test_Bean; procedure Process (Pattern : in String; Route : in Route_Type_Access) is begin T.Assert (Route /= null, "The route is null for " & Pattern); T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern); Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index)); T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all, "Invalid route for " & Pattern); end Process; begin for I in Path_Array'Range loop Add_Route (T, Router, Path_Array (I).all, I, Bean); end loop; Router.Iterate (Process'Access); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.html", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (fixed path)"); end; declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (extension)"); end; end Test_Iterate; end ASF.Routes.Tests;
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Measures; with Util.Log.Loggers; with Util.Test_Caller; with EL.Contexts.Default; package body ASF.Routes.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Routes.Tests"); package Caller is new Util.Test_Caller (Test, "Routes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (fixed path)", Test_Add_Route_With_Path'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (:param path)", Test_Add_Route_With_Param'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (*.ext path)", Test_Add_Route_With_Ext'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Add_Route (#{} path)", Test_Add_Route_With_EL'Access); Caller.Add_Test (Suite, "Test ASF.Routes.Iterate", Test_Iterate'Access); end Add_Tests; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "id" then return Util.Beans.Objects.To_Object (Bean.Id); elsif Name = "name" then return Util.Beans.Objects.To_Object (Bean.Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then Bean.Id := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "name" then Bean.Name := Util.Beans.Objects.To_Unbounded_String (Value); end if; end Set_Value; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is begin T.Bean := new Test_Bean; ASF.Tests.EL_Test (T).Set_Up; T.Root_Resolver.Register (Ada.Strings.Unbounded.To_Unbounded_String ("user"), Util.Beans.Objects.To_Object (T.Bean.all'Access)); for I in T.Routes'Range loop T.Routes (I) := Route_Type_Refs.Create (new Test_Route_Type '(Util.Refs.Ref_Entity with Index => I)); end loop; end Set_Up; -- ------------------------------ -- Verify that the path matches the given route. -- ------------------------------ procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).Value; R : Route_Context_Type; begin Router.Find_Route (Path, R); declare P : constant String := Get_Path (R); begin T.Assert_Equals (Path, P, "Add_Route + Find_Route with " & Path); T.Assert (Get_Route (R) /= null, "Get_Route returns a null route for " & Path); T.Assert (Get_Route (R) = Route, "Get_Route returns a wrong route for " & Path); -- Inject the path parameters in the bean instance. Inject_Parameters (R, Bean, T.ELContext.all); end; end Verify_Route; -- ------------------------------ -- Add the route associted with the path pattern. -- ------------------------------ procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class) is Route : constant Route_Type_Access := T.Routes (Index).Value; begin Router.Add_Route (Path, Route, T.ELContext.all); Verify_Route (T, Router, Path, Index, Bean); end Add_Route; -- ------------------------------ -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html -- ------------------------------ procedure Test_Add_Route_With_Path (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/page.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); Verify_Route (T, Router, "/list/index.html", 3, Bean); end Test_Add_Route_With_Path; -- ------------------------------ -- Test the Add_Route with extension mapping. -- Example: /list/*.html -- ------------------------------ procedure Test_Add_Route_With_Ext (T : in out Test) is Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/page.html", 1, Bean); Add_Route (T, Router, "/list/*.html", 2, Bean); Add_Route (T, Router, "/list/index.html", 3, Bean); Add_Route (T, Router, "/view/page/content/page1.html", 4, Bean); Add_Route (T, Router, "/view/page/content/page2.html", 5, Bean); Add_Route (T, Router, "/view/page/content/*.html", 6, Bean); Add_Route (T, Router, "/ajax/*", 7, Bean); Add_Route (T, Router, "*.html", 8, Bean); -- Verify precedence and wildcard matching. Verify_Route (T, Router, "/list/index.html", 3, Bean); Verify_Route (T, Router, "/list/admin.html", 2, Bean); Verify_Route (T, Router, "/list/1/2/3/admin.html", 2, Bean); Verify_Route (T, Router, "/view/page/content/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/t.html", 6, Bean); Verify_Route (T, Router, "/view/page/content/1/2/t.html", 6, Bean); Verify_Route (T, Router, "/ajax/form/save", 7, Bean); Verify_Route (T, Router, "/view/index.html", 8, Bean); Add_Route (T, Router, "/ajax/timeKeeper/*", 9, Bean); Verify_Route (T, Router, "/ajax/form/save", 7, Bean); Verify_Route (T, Router, "/ajax/timeKeeper/save", 9, Bean); end Test_Add_Route_With_Ext; -- ------------------------------ -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html -- ------------------------------ procedure Test_Add_Route_With_Param (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : Test_Bean; begin Add_Route (T, Router, "/users/:id/view.html", 1, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/list.html", 2, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/users/:id/index.html", 3, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); Bean.Id := To_Unbounded_String (""); Add_Route (T, Router, "/view/page/content/index.html", 4, Bean); Add_Route (T, Router, "/list//page/view.html", 5, Bean); Add_Route (T, Router, "/list////page/content.html", 6, Bean); T.Assert_Equals ("", To_String (Bean.Id), "Bean injection failed for fixed path"); Add_Route (T, Router, "/users/:id/:name/index.html", 7, Bean); T.Assert_Equals (":id", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals (":name", To_String (Bean.Name), "Bean injection failed for :name"); Add_Route (T, Router, "/users/list/index.html", 8, Bean); Verify_Route (T, Router, "/users/1234/view.html", 1, Bean); T.Assert_Equals ("1234", To_String (Bean.Id), "Bean injection failed for :id"); Verify_Route (T, Router, "/users/234/567/index.html", 7, Bean); T.Assert_Equals ("234", To_String (Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_Param; -- ------------------------------ -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html -- ------------------------------ procedure Test_Add_Route_With_EL (T : in out Test) is use Ada.Strings.Unbounded; Router : Router_Type; Bean : aliased Test_Bean; begin Add_Route (T, Router, "/users/#{user.id}", 1, Bean); Add_Route (T, Router, "/users/view.html", 2, Bean); Add_Route (T, Router, "/users/#{user.id}/#{user.name}/index.html", 3, Bean); Add_Route (T, Router, "/users/admin/#{user.id}/pages/#{user.name}", 4, Bean); -- Verify that the path parameters are injected in the 'user' bean (= T.Bean). Verify_Route (T, Router, "/users/234/567/index.html", 3, Bean); T.Assert_Equals ("234", To_String (T.Bean.Id), "Bean injection failed for :id"); T.Assert_Equals ("567", To_String (T.Bean.Name), "Bean injection failed for :name"); end Test_Add_Route_With_EL; P_1 : aliased constant String := "/list/index.html"; P_2 : aliased constant String := "/users/:id"; P_3 : aliased constant String := "/users/:id/view"; P_4 : aliased constant String := "/users/index.html"; P_5 : aliased constant String := "/users/:id/:name"; P_6 : aliased constant String := "/users/:id/:name/view.html"; P_7 : aliased constant String := "/users/:id/list"; P_8 : aliased constant String := "/users/test.html"; P_9 : aliased constant String := "/admin/1/2/3/4/5/list.html"; P_10 : aliased constant String := "/admin/*.html"; P_11 : aliased constant String := "/admin/*.png"; P_12 : aliased constant String := "/admin/*.jpg"; P_13 : aliased constant String := "/users/:id/page/*.xml"; P_14 : aliased constant String := "/*.jsf"; type Const_String_Access is access constant String; type String_Array is array (Positive range <>) of Const_String_Access; Path_Array : constant String_Array := (P_1'Access, P_2'Access, P_3'Access, P_4'Access, P_5'Access, P_6'Access, P_7'Access, P_8'Access, P_9'Access, P_10'Access, P_11'Access, P_12'Access, P_13'Access, P_14'Access); -- ------------------------------ -- Test the Iterate over several paths. -- ------------------------------ procedure Test_Iterate (T : in out Test) is Router : Router_Type; Bean : Test_Bean; procedure Process (Pattern : in String; Route : in Route_Type_Access) is begin T.Assert (Route /= null, "The route is null for " & Pattern); T.Assert (Route.all in Test_Route_Type'Class, "Invalid route for " & Pattern); Log.Info ("Route {0} to {1}", Pattern, Natural'Image (Test_Route_Type (Route.all).Index)); T.Assert_Equals (Pattern, Path_Array (Test_Route_Type (Route.all).Index).all, "Invalid route for " & Pattern); end Process; begin for I in Path_Array'Range loop Add_Route (T, Router, Path_Array (I).all, I, Bean); end loop; Router.Iterate (Process'Access); declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.html", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (fixed path)"); end; declare St : Util.Measures.Stamp; begin for I in 1 .. 1000 loop declare R : Route_Context_Type; begin Router.Find_Route ("/admin/1/2/3/4/5/list.jsf", R); end; end loop; Util.Measures.Report (St, "Find 1000 routes (extension)"); end; end Test_Iterate; end ASF.Routes.Tests;
Add a testcase for wildcard route match
Add a testcase for wildcard route match
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
ba4188a8b0776cdd35bed6e3dea8f38792edf4e1
src/wiki-filters.ads
src/wiki-filters.ads
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; with Wiki.Attributes; with Wiki.Documents; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt> -- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations -- and it forwards the different calls to a next wiki document instance. A filter can do some -- operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type -- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- package Wiki.Filters is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Nodes.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; 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 (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document); private type Filter_Type is new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; with Wiki.Attributes; with Wiki.Nodes; with Wiki.Strings; -- == Filters == -- The <b>Wiki.Filters</b> package provides a simple filter framework that allows to plug -- specific filters when a wiki document is parsed and processed. The <tt>Filter_Type</tt> -- implements the <tt>Document_Reader</tt> interface to catch all the wiki document operations -- and it forwards the different calls to a next wiki document instance. A filter can do some -- operations while calls are made so that it can: -- -- * Get the text content and filter it by looking at forbidden words in some dictionary, -- * Ignore some formatting construct (for example to forbid the use of links), -- * Verify and do some corrections on HTML content embedded in wiki text, -- * Expand some plugins, specific links to complex content. -- -- To implement a new filter, the <tt>Filter_Type</tt> type must be used as a base type -- and some of the operations have to be overriden. The default <tt>Filter_Type</tt> operations -- just propagate the call to the attached wiki document instance (ie, a kind of pass -- through filter). -- package Wiki.Filters is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- Filter type -- ------------------------------ type Filter_Type is new Ada.Finalization.Limited_Controlled with private; type Filter_Type_Access is access all Filter_Type'Class; -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Kind : in Wiki.Nodes.Simple_Node_Kind); -- Add a text content with the given format to the document. procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Add a section header with the given level in the document. procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Header : in Wiki.Strings.WString; Level : in Natural); -- Push a HTML node with the given tag to the document. procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Pop a HTML node with the given tag. procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Tag : in Wiki.Nodes.Html_Tag_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; 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 (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Level : in Positive; Ordered : in Boolean); -- Add a link. procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add an image. procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a quote. procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List_Type); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document; Text : in Wiki.Strings.WString; Format : in Unbounded_Wide_Wide_String); -- Finish the document after complete wiki text has been parsed. procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Nodes.Document); private type Filter_Type is new Ada.Finalization.Limited_Controlled with record Next : Filter_Type_Access; end record; end Wiki.Filters;
Use the Wiki.Format_Map type and drop the Wiki.Documents dependency
Use the Wiki.Format_Map type and drop the Wiki.Documents dependency
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
440a1d61c101ff624e1146d69eb48c8304588520
src/wiki-strings.ads
src/wiki-strings.ads
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- 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.Strings.Wide_Wide_Unbounded; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; function Is_Alphanumeric (C : in WChar) return Boolean renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- 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.Strings.Wide_Wide_Unbounded; with Ada.Strings.Wide_Wide_Maps; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Ada.Strings.Wide_Wide_Fixed; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; subtype WChar_Mapping is Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Mapping; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; function Is_Alphanumeric (C : in WChar) return Boolean renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric; function Index (S : in WString; P : in WString; Going : in Ada.Strings.Direction := Ada.Strings.Forward; Mapping : in WChar_Mapping := Ada.Strings.Wide_Wide_Maps.Identity) return Natural renames Ada.Strings.Wide_Wide_Fixed.Index; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
Declare WChar_Mapping type and Index function
Declare WChar_Mapping type and Index function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ca75e6900380036a05c5ce6330dc232c0c79af27
mat/src/mat-formats.ads
mat/src/mat-formats.ads
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Formats is -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events.Targets; package MAT.Formats is -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String; end MAT.Formats;
Declare the Event function to format an event in a printable short description
Declare the Event function to format an event in a printable short description
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d694507eeba50b3b48430b16d1af5317015bdd3f
regtests/util-streams-files-tests.adb
regtests/util-streams-files-tests.adb
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Files; with Util.Streams.Buffered; package body Util.Streams.Files.Tests is use Util.Tests; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Files.Create, Write, Flush, Close", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Files.Write, Flush", Test_Write'Access); end Add_Tests; -- ------------------------------ -- Test reading and writing on a buffered stream with various buffer sizes -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : aliased File_Stream; Buffer : Util.Streams.Buffered.Buffered_Stream; begin for I in 1 .. 32 loop Buffer.Initialize (Output => Stream'Unchecked_Access, Input => null, Size => I); Stream.Create (Mode => Out_File, Name => "test-stream.txt"); Buffer.Write ("abcd"); Buffer.Write (" fghij"); Buffer.Flush; Stream.Close; declare Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => "test-stream.txt", Into => Content, Max_Size => 10000); Assert_Equals (T, "abcd fghij", Content, "Invalid content written to the file stream"); end; end loop; end Test_Read_Write; procedure Test_Write (T : in out Test) is begin null; end Test_Write; end Util.Streams.Files.Tests;
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Files; with Util.Streams.Texts; package body Util.Streams.Files.Tests is use Util.Tests; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Files.Create, Write, Flush, Close", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Files.Write, Flush", Test_Write'Access); end Add_Tests; -- ------------------------------ -- Test reading and writing on a buffered stream with various buffer sizes -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : aliased File_Stream; Buffer : Util.Streams.Texts.Print_Stream; begin for I in 1 .. 32 loop Buffer.Initialize (Output => Stream'Unchecked_Access, Input => null, Size => I); Stream.Create (Mode => Out_File, Name => "test-stream.txt"); Buffer.Write ("abcd"); Buffer.Write (" fghij"); Buffer.Flush; Stream.Close; declare Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => "test-stream.txt", Into => Content, Max_Size => 10000); Assert_Equals (T, "abcd fghij", Content, "Invalid content written to the file stream"); end; end loop; end Test_Read_Write; procedure Test_Write (T : in out Test) is begin null; end Test_Write; end Util.Streams.Files.Tests;
Use a Print_Stream for the test
Use a Print_Stream for the test
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
225ddf74376da5a89f53dbcde8eea57064ecee76
src/gen-commands-distrib.ads
src/gen-commands-distrib.ads
----------------------------------------------------------------------- -- gen-commands-distrib -- Distrib command for dynamo -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Distrib is -- ------------------------------ -- Distrib Command -- ------------------------------ 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.Distrib;
----------------------------------------------------------------------- -- gen-commands-distrib -- Distrib command for dynamo -- 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.Distrib is -- ------------------------------ -- Distrib Command -- ------------------------------ 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.Distrib;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
296af56dda7eb3088231c191ea013f5dd13336a9
src/util-strings-builders.ads
src/util-strings-builders.ads
----------------------------------------------------------------------- -- Util-strings-builders -- Set of strings -- 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.Texts.Builders; -- The <b>Util.Strings.Builders</b> package provides an instantiation -- of a text builders for <tt>Character</tt> and <tt>String</tt> types. package Util.Strings.Builders is new Util.Texts.Builders (Element_Type => Character, Input => String);
----------------------------------------------------------------------- -- util-strings-builders -- Set of strings -- Copyright (C) 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.Texts.Builders; -- The <b>Util.Strings.Builders</b> package provides an instantiation -- of a text builders for <tt>Character</tt> and <tt>String</tt> types. package Util.Strings.Builders is new Util.Texts.Builders (Element_Type => Character, Input => String);
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f2240f187b9d05222cfe246372dbbff90cfa7848
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.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); -- Add a text block that is pre-formatted. procedure Add_Preformatted (Engine : in out Wiki_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in 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 type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Open_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Open_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
Rename Add_Preformatted into Render_Preformatted
Rename Add_Preformatted into Render_Preformatted
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
7658a3cdda0482aa41b26f50bcc481d1238d8b4a
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 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;
------------------------------------------------------------------------------ -- 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 Dict_Sources is type Enum is (S_Expression, Word_List); end Dict_Sources; package Options is type Id is (Output_Ada_Dict, Dictionary_Input, Decode, Encode, Output_Hash, Help, Stat_Output, No_Stat_Output, Word_List_Input, 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; Dict_Source : Dict_Sources.Enum := Dict_Sources.S_Expression; 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 function To_Dictionary (Handler : in Callback'Class; Input : in Natools.Smaz.Tools.String_Lists.List) return Natools.Smaz.Dictionary; -- Convert the input into a dictionary given the option in Handler 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_Dict => 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; when Options.Dictionary_Input => Handler.Dict_Source := Dict_Sources.S_Expression; when Options.Word_List_Input => Handler.Dict_Source := Dict_Sources.Word_List; 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_Dict); R.Add_Option ("decode", 'd', No_Argument, Decode); R.Add_Option ("dict", 'D', No_Argument, Dictionary_Input); 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 ("word-list", 'w', No_Argument, Word_List_Input); 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_Dict => 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"); when Options.Dictionary_Input => New_Line (Output); Put_Line (Output, Indent & Indent & "Read dictionary directly in input S-expression (default)"); when Options.Word_List_Input => New_Line (Output); Put_Line (Output, Indent & Indent & "Compute dictionary from word list in input S-expression"); end case; end loop; end Print_Help; function To_Dictionary (Handler : in Callback'Class; Input : in Natools.Smaz.Tools.String_Lists.List) return Natools.Smaz.Dictionary is begin case Handler.Dict_Source is when Dict_Sources.S_Expression => return Natools.Smaz.Tools.To_Dictionary (Input, True); when Dict_Sources.Word_List => declare Counter : Natools.Smaz.Tools.Word_Counter; begin for S of Input loop Natools.Smaz.Tools.Add_Substrings (Counter, S, 1, 3); end loop; return Natools.Smaz.Tools.To_Dictionary (Natools.Smaz.Tools.Most_Common_Words (Counter, 254), True); end; end case; end To_Dictionary; 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 := To_Dictionary (Handler, Input_List); 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 support for dictionary generation from a word list
tools/smaz: add support for dictionary generation from a word list
Ada
isc
faelys/natools
73fe0a3ff327d91f4bda9b508bf914fb6d21b4d1
src/orka/interface/orka-base64.ads
src/orka/interface/orka-base64.ads
-- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Streams; private package Orka.Base64 is pragma Preelaborate; use Ada.Streams; Data_Prefix : constant String; function Base64_Encoded (Text : String) return Boolean is (Text'Length >= Data_Prefix'Length and then Text (Text'First .. Data_Prefix'Length) = Data_Prefix) with Inline; function Decode (Input : String) return Stream_Element_Array; Encoding_Error : exception; private Data_Prefix : constant String := "data:text/plain;base64,"; end Orka.Base64;
-- 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.Streams; private package Orka.Base64 is pragma Preelaborate; use Ada.Streams; Data_Prefix : constant String; function Base64_Encoded (Text : String) return Boolean is (Text'Length >= Data_Prefix'Length and then Text (Text'First .. Text'First + Data_Prefix'Length - 1) = Data_Prefix) with Inline; function Decode (Input : String) return Stream_Element_Array; Encoding_Error : exception; private Data_Prefix : constant String := "data:text/plain;base64,"; end Orka.Base64;
Fix Base64_Encoded function
orka: Fix Base64_Encoded function Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
b90e2d067e7da97a340395ef127531d3d0252151
mat/src/gtk/gtkmatp.adb
mat/src/gtk/gtkmatp.adb
----------------------------------------------------------------------- -- gtkmatp -- Gtk MAT application -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Targets.Gtkmat; with Gtk.Widget; procedure GtkMatp is Main : Gtk.Widget.Gtk_Widget; Target : MAT.Targets.Gtkmat.Target_Type; begin Target.Initialize_Options; Target.Initialize_Widget (Main); MAT.Commands.Initialize_Files (Target); Target.Start; Target.Interactive; Target.Stop; end GtkMatp;
----------------------------------------------------------------------- -- gtkmatp -- Gtk MAT application -- 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.Commands; with MAT.Targets; with MAT.Targets.Gtkmat; with Gtk.Widget; procedure GtkMatp is Main : Gtk.Widget.Gtk_Widget; Target : aliased MAT.Targets.Gtkmat.Target_Type; begin Target.Initialize_Options; Target.Initialize_Widget (Main); MAT.Commands.Initialize_Files (Target); Target.Start; Target.Interactive; Target.Stop; end GtkMatp;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ec9de16ae2d9f47983b1833318a8e8a7d9c4d32f
src/gen-commands-docs.adb
src/gen-commands-docs.adb
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Text_IO; with Gen.Artifacts.Docs; with Gen.Model.Packages; package body Gen.Commands.Docs is use GNAT.Command_Line; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); Doc : Gen.Artifacts.Docs.Artifact; M : Gen.Model.Packages.Model_Definition; begin Generator.Read_Project ("dynamo.xml", False); -- Setup the target directory where the distribution is created. declare Target_Dir : constant String := Get_Argument; begin if Target_Dir'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Target_Dir); end; Doc.Prepare (M, Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("build-doc: Extract and generate the project documentation"); Put_Line ("Usage: build-doc"); New_Line; Put_Line (" Extract the documentation from the project source files and generate the"); Put_Line (" project documentation. The following files are scanned:"); Put_Line (" - Ada specifications (src/*.ads)"); Put_Line (" - XML configuration files (config/*.xml)"); Put_Line (" - XML database model files (db/*.xml)"); end Help; end Gen.Commands.Docs;
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- 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 GNAT.Command_Line; with Ada.Text_IO; with Gen.Artifacts.Docs; with Gen.Model.Packages; package body Gen.Commands.Docs is use GNAT.Command_Line; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); Doc : Gen.Artifacts.Docs.Artifact; M : Gen.Model.Packages.Model_Definition; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; begin Generator.Read_Project ("dynamo.xml", False); if Arg1'Length = 0 then Generator.Error ("Missing target directory"); return; elsif Arg1 (Arg1'First) /= '-' then if Arg2'Length /= 0 then Generator.Error ("Invalid markup option " & Arg1); return; end if; -- Setup the target directory where the distribution is created. Generator.Set_Result_Directory (Arg1); else if Arg1 = "-markdown" then Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN; elsif Arg1 = "-google" then Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; else Generator.Error ("Invalid markup option " & Arg1); return; end if; if Arg2'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Arg2); end if; Doc.Set_Format (Fmt); Doc.Prepare (M, Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("build-doc: Extract and generate the project documentation"); Put_Line ("Usage: build-doc [-markdown|-google] target-dir"); New_Line; Put_Line (" Extract the documentation from the project source files and generate the"); Put_Line (" project documentation. The following files are scanned:"); Put_Line (" - Ada specifications (src/*.ads)"); Put_Line (" - XML configuration files (config/*.xml)"); Put_Line (" - XML database model files (db/*.xml)"); end Help; end Gen.Commands.Docs;
Add new optional option to the build-doc command to configure the output documentation format
Add new optional option to the build-doc command to configure the output documentation format
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0c07f4edbcad75ccfe45adfc2a16a9d7f89d3a3a
src/wiki-attributes.adb
src/wiki-attributes.adb
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return To_Unbounded_Wide_Wide_String (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Unbounded_Wide_Wide_String is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Null_Unbounded_Wide_Wide_String; end if; end Get_Attribute; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is begin Append (List, Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Name), Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Val : constant Wiki.Strings.WString := To_Wide_Wide_String (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List) is begin List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List) is begin List.Clear; end Finalize; end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body Wiki.Attributes is use Ada.Characters; -- ------------------------------ -- Get the attribute name. -- ------------------------------ function Get_Name (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Name; end Get_Name; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Position : in Cursor) return String is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Ada.Characters.Conversions.To_String (Attr.Value.Value); end Get_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Wide_Value (Position : in Cursor) return Wiki.Strings.WString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Attr.Value.Value; end Get_Wide_Value; -- ------------------------------ -- Get the attribute wide value. -- ------------------------------ function Get_Unbounded_Wide_Value (Position : in Cursor) return Wiki.Strings.UString is Attr : constant Attribute_Ref := Attribute_Vectors.Element (Position.Pos); begin return Wiki.Strings.To_UString (Attr.Value.Value); end Get_Unbounded_Wide_Value; -- ------------------------------ -- Returns True if the cursor has a valid attribute. -- ------------------------------ function Has_Element (Position : in Cursor) return Boolean is begin return Attribute_Vectors.Has_Element (Position.Pos); end Has_Element; -- ------------------------------ -- Move the cursor to the next attribute. -- ------------------------------ procedure Next (Position : in out Cursor) is begin Attribute_Vectors.Next (Position.Pos); end Next; -- ------------------------------ -- Find the attribute with the given name. -- ------------------------------ function Find (List : in Attribute_List; Name : in String) return Cursor is Iter : Attribute_Vectors.Cursor := List.List.First; begin while Attribute_Vectors.Has_Element (Iter) loop declare Attr : constant Attribute_Ref := Attribute_Vectors.Element (Iter); begin if Attr.Value.Name = Name then return Cursor '(Pos => Iter); end if; end; Attribute_Vectors.Next (Iter); end loop; return Cursor '(Pos => Iter); end Find; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.UString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Unbounded_Wide_Value (Attr); else return Wiki.Strings.Null_UString; end if; end Get_Attribute; -- ------------------------------ -- Find the attribute with the given name and return its value. -- ------------------------------ function Get_Attribute (List : in Attribute_List; Name : in String) return Wiki.Strings.WString is Attr : constant Cursor := Find (List, Name); begin if Has_Element (Attr) then return Get_Wide_Value (Attr); else return ""; end if; end Get_Attribute; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.WString; Value : in Wiki.Strings.WString) is Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Value'Length, Name => Conversions.To_String (Name), Value => Value); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in Wiki.Strings.UString; Value : in Wiki.Strings.UString) is begin Append (List, Wiki.Strings.To_WString (Name), Wiki.Strings.To_WString (Value)); end Append; -- ------------------------------ -- Append the attribute to the attribute list. -- ------------------------------ procedure Append (List : in out Attribute_List; Name : in String; Value : in Wiki.Strings.UString) is Val : constant Wiki.Strings.WString := Wiki.Strings.To_WString (Value); Attr : constant Attribute_Access := new Attribute '(Util.Refs.Ref_Entity with Name_Length => Name'Length, Value_Length => Val'Length, Name => Name, Value => Val); begin List.List.Append (Attribute_Refs.Create (Attr)); end Append; -- ------------------------------ -- Get the cursor to get access to the first attribute. -- ------------------------------ function First (List : in Attribute_List) return Cursor is begin return Cursor '(Pos => List.List.First); end First; -- ------------------------------ -- Get the number of attributes in the list. -- ------------------------------ function Length (List : in Attribute_List) return Natural is begin return Natural (List.List.Length); end Length; -- ------------------------------ -- Clear the list and remove all existing attributes. -- ------------------------------ procedure Clear (List : in out Attribute_List) is begin List.List.Clear; end Clear; -- ------------------------------ -- Iterate over the list attributes and call the <tt>Process</tt> procedure. -- ------------------------------ procedure Iterate (List : in Attribute_List; Process : not null access procedure (Name : in String; Value : in Wiki.Strings.WString)) is Iter : Attribute_Vectors.Cursor := List.List.First; Item : Attribute_Ref; begin while Attribute_Vectors.Has_Element (Iter) loop Item := Attribute_Vectors.Element (Iter); Process (Item.Value.Name, Item.Value.Value); Attribute_Vectors.Next (Iter); end loop; end Iterate; -- ------------------------------ -- Finalize the attribute list releasing any storage. -- ------------------------------ overriding procedure Finalize (List : in out Attribute_List) is begin List.Clear; end Finalize; end Wiki.Attributes;
Use the Wiki.Strings.UString type
Use the Wiki.Strings.UString type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d1fbf385d4ab5f91f1b55d3c3b81d726278ee38f
src/file_operations.adb
src/file_operations.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Directories; with Ada.Direct_IO; with Ada.Text_IO; with HelperText; package body File_Operations is package DIR renames Ada.Directories; package TIO renames Ada.Text_IO; package HT renames HelperText; -------------------------------------------------------------------------------------------- -- get_file_contents -------------------------------------------------------------------------------------------- function get_file_contents (dossier : String) return String is File_Size : Natural := Natural (DIR.Size (dossier)); subtype File_String is String (1 .. File_Size); package File_String_IO is new Ada.Direct_IO (File_String); file_handle : File_String_IO.File_Type; contents : File_String; attempts : Natural := 0; begin if File_Size = 0 then return ""; end if; -- The introduction of variants causes a buildsheet to be scanned once per variant. -- It's possible (even common) for simultaneous requests to scan the same buildsheet to -- occur. Thus, if the file is already open, wait and try again (up to 5 times) loop begin File_String_IO.Open (File => file_handle, Mode => File_String_IO.In_File, Name => dossier); exit; exception when File_String_IO.Status_Error | File_String_IO.Use_Error => if attempts = 5 then raise file_handling with "get_file_contents: remained open: " & dossier; end if; attempts := attempts + 1; delay 0.1; end; end loop; File_String_IO.Read (File => file_handle, Item => contents); File_String_IO.Close (file_handle); return contents; exception when others => if File_String_IO.Is_Open (file_handle) then File_String_IO.Close (file_handle); end if; raise file_handling with "get_file_contents: " & dossier; end get_file_contents; -------------------------------------------------------------------------------------------- -- dump_contents_to_file -------------------------------------------------------------------------------------------- procedure dump_contents_to_file (contents : String; dossier : String) is File_Size : Natural := contents'Length; subtype File_String is String (1 .. File_Size); package File_String_IO is new Ada.Direct_IO (File_String); file_handle : File_String_IO.File_Type; begin mkdirp_from_filename (dossier); File_String_IO.Create (File => file_handle, Mode => File_String_IO.Out_File, Name => dossier); File_String_IO.Write (File => file_handle, Item => contents); File_String_IO.Close (file_handle); exception when others => if File_String_IO.Is_Open (file_handle) then File_String_IO.Close (file_handle); end if; raise file_handling; end dump_contents_to_file; -------------------------------------------------------------------------------------------- -- create_subdirectory -------------------------------------------------------------------------------------------- procedure create_subdirectory (extraction_directory : String; subdirectory : String) is abspath : String := extraction_directory & "/" & subdirectory; begin if subdirectory = "" then return; end if; if not DIR.Exists (abspath) then DIR.Create_Directory (abspath); end if; end create_subdirectory; -------------------------------------------------------------------------------------------- -- head_n1 -------------------------------------------------------------------------------------------- function head_n1 (filename : String) return String is handle : TIO.File_Type; begin TIO.Open (File => handle, Mode => TIO.In_File, Name => filename); if TIO.End_Of_File (handle) then TIO.Close (handle); return ""; end if; declare line : constant String := TIO.Get_Line (handle); begin TIO.Close (handle); return line; end; end head_n1; -------------------------------------------------------------------------------------------- -- create_pidfile -------------------------------------------------------------------------------------------- procedure create_pidfile (pidfile : String) is pidtext : constant String := HT.int2str (Get_PID); handle : TIO.File_Type; begin TIO.Create (File => handle, Mode => TIO.Out_File, Name => pidfile); TIO.Put_Line (handle, pidtext); TIO.Close (handle); end create_pidfile; -------------------------------------------------------------------------------------------- -- destroy_pidfile -------------------------------------------------------------------------------------------- procedure destroy_pidfile (pidfile : String) is begin if DIR.Exists (pidfile) then DIR.Delete_File (pidfile); end if; exception when others => null; end destroy_pidfile; -------------------------------------------------------------------------------------------- -- mkdirp_from_filename -------------------------------------------------------------------------------------------- procedure mkdirp_from_filename (filename : String) is condir : String := DIR.Containing_Directory (Name => filename); begin DIR.Create_Path (New_Directory => condir); end mkdirp_from_filename; -------------------------------------------------------------------------------------------- -- concatenate_file -------------------------------------------------------------------------------------------- procedure concatenate_file (basefile : String; another_file : String) is handle : TIO.File_Type; begin if not DIR.Exists (another_file) then raise file_handling with "concatenate_file: new_file does not exist => " & another_file; end if; if DIR.Exists (basefile) then TIO.Open (File => handle, Mode => TIO.Append_File, Name => basefile); declare contents : constant String := get_file_contents (another_file); begin TIO.Put (handle, contents); end; TIO.Close (handle); else DIR.Copy_File (Source_Name => another_file, Target_Name => basefile); end if; exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; raise file_handling; end concatenate_file; -------------------------------------------------------------------------------------------- -- create_cookie -------------------------------------------------------------------------------------------- procedure create_cookie (fullpath : String) is subtype File_String is String (1 .. 1); package File_String_IO is new Ada.Direct_IO (File_String); file_handle : File_String_IO.File_Type; begin mkdirp_from_filename (fullpath); File_String_IO.Create (File => file_handle, Mode => File_String_IO.Out_File, Name => fullpath); File_String_IO.Close (file_handle); exception when others => raise file_handling; end create_cookie; -------------------------------------------------------------------------------------------- -- replace_directory_contents -------------------------------------------------------------------------------------------- procedure replace_directory_contents (source_directory : String; target_directory : String; pattern : String) is search : DIR.Search_Type; dirent : DIR.Directory_Entry_Type; filter : constant DIR.Filter_Type := (DIR.Ordinary_File => True, others => False); begin DIR.Start_Search (Search => search, Directory => target_directory, Pattern => pattern, Filter => filter); while DIR.More_Entries (search) loop DIR.Get_Next_Entry (search, dirent); declare SN : constant String := DIR.Simple_Name (dirent); oldfile : constant String := target_directory & "/" & SN; newfile : constant String := source_directory & "/" & SN; begin if DIR.Exists (newfile) then DIR.Copy_File (Source_Name => newfile, Target_Name => oldfile); end if; exception when others => TIO.Put_Line ("Failed to copy " & newfile & " over to " & oldfile); end; end loop; DIR.End_Search (search); end replace_directory_contents; end File_Operations;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Directories; with Ada.Direct_IO; with Ada.Text_IO; with HelperText; package body File_Operations is package DIR renames Ada.Directories; package TIO renames Ada.Text_IO; package HT renames HelperText; -------------------------------------------------------------------------------------------- -- get_file_contents -------------------------------------------------------------------------------------------- function get_file_contents (dossier : String) return String is File_Size : Natural := Natural (DIR.Size (dossier)); subtype File_String is String (1 .. File_Size); package File_String_IO is new Ada.Direct_IO (File_String); file_handle : File_String_IO.File_Type; contents : File_String; attempts : Natural := 0; begin if File_Size = 0 then return ""; end if; -- The introduction of variants causes a buildsheet to be scanned once per variant. -- It's possible (even common) for simultaneous requests to scan the same buildsheet to -- occur. Thus, if the file is already open, wait and try again (up to 5 times) loop begin File_String_IO.Open (File => file_handle, Mode => File_String_IO.In_File, Name => dossier); exit; exception when File_String_IO.Status_Error | File_String_IO.Use_Error => if attempts = 5 then raise file_handling with "get_file_contents: remained open: " & dossier; end if; attempts := attempts + 1; delay 0.1; end; end loop; File_String_IO.Read (File => file_handle, Item => contents); File_String_IO.Close (file_handle); return contents; exception when others => if File_String_IO.Is_Open (file_handle) then File_String_IO.Close (file_handle); end if; raise file_handling with "get_file_contents: " & dossier; end get_file_contents; -------------------------------------------------------------------------------------------- -- dump_contents_to_file -------------------------------------------------------------------------------------------- procedure dump_contents_to_file (contents : String; dossier : String) is File_Size : Natural := contents'Length; subtype File_String is String (1 .. File_Size); package File_String_IO is new Ada.Direct_IO (File_String); file_handle : File_String_IO.File_Type; begin mkdirp_from_filename (dossier); File_String_IO.Create (File => file_handle, Mode => File_String_IO.Out_File, Name => dossier); File_String_IO.Write (File => file_handle, Item => contents); File_String_IO.Close (file_handle); exception when others => if File_String_IO.Is_Open (file_handle) then File_String_IO.Close (file_handle); end if; raise file_handling; end dump_contents_to_file; -------------------------------------------------------------------------------------------- -- create_subdirectory -------------------------------------------------------------------------------------------- procedure create_subdirectory (extraction_directory : String; subdirectory : String) is abspath : String := extraction_directory & "/" & subdirectory; begin if subdirectory = "" then return; end if; if not DIR.Exists (abspath) then DIR.Create_Directory (abspath); end if; end create_subdirectory; -------------------------------------------------------------------------------------------- -- head_n1 -------------------------------------------------------------------------------------------- function head_n1 (filename : String) return String is handle : TIO.File_Type; begin TIO.Open (File => handle, Mode => TIO.In_File, Name => filename); if TIO.End_Of_File (handle) then TIO.Close (handle); return ""; end if; declare line : constant String := TIO.Get_Line (handle); begin TIO.Close (handle); return line; end; end head_n1; -------------------------------------------------------------------------------------------- -- create_pidfile -------------------------------------------------------------------------------------------- procedure create_pidfile (pidfile : String) is pidtext : constant String := HT.int2str (Get_PID); handle : TIO.File_Type; begin TIO.Create (File => handle, Mode => TIO.Out_File, Name => pidfile); TIO.Put_Line (handle, pidtext); TIO.Close (handle); end create_pidfile; -------------------------------------------------------------------------------------------- -- destroy_pidfile -------------------------------------------------------------------------------------------- procedure destroy_pidfile (pidfile : String) is begin if DIR.Exists (pidfile) then DIR.Delete_File (pidfile); end if; exception when others => null; end destroy_pidfile; -------------------------------------------------------------------------------------------- -- mkdirp_from_filename -------------------------------------------------------------------------------------------- procedure mkdirp_from_filename (filename : String) is condir : String := DIR.Containing_Directory (Name => filename); begin DIR.Create_Path (New_Directory => condir); end mkdirp_from_filename; -------------------------------------------------------------------------------------------- -- concatenate_file -------------------------------------------------------------------------------------------- procedure concatenate_file (basefile : String; another_file : String) is handle : TIO.File_Type; begin if not DIR.Exists (another_file) then raise file_handling with "concatenate_file: new_file does not exist => " & another_file; end if; if DIR.Exists (basefile) then TIO.Open (File => handle, Mode => TIO.Append_File, Name => basefile); declare contents : constant String := get_file_contents (another_file); begin TIO.Put (handle, contents); end; TIO.Close (handle); else DIR.Copy_File (Source_Name => another_file, Target_Name => basefile); end if; exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; raise file_handling; end concatenate_file; -------------------------------------------------------------------------------------------- -- create_cookie -------------------------------------------------------------------------------------------- procedure create_cookie (fullpath : String) is subtype File_String is String (1 .. 1); package File_String_IO is new Ada.Direct_IO (File_String); file_handle : File_String_IO.File_Type; begin mkdirp_from_filename (fullpath); File_String_IO.Create (File => file_handle, Mode => File_String_IO.Out_File, Name => fullpath); File_String_IO.Close (file_handle); exception when others => raise file_handling; end create_cookie; -------------------------------------------------------------------------------------------- -- replace_directory_contents -------------------------------------------------------------------------------------------- procedure replace_directory_contents (source_directory : String; target_directory : String; pattern : String) is search : DIR.Search_Type; dirent : DIR.Directory_Entry_Type; filter : constant DIR.Filter_Type := (DIR.Ordinary_File => True, others => False); begin if not DIR.Exists (target_directory) then return; end if; DIR.Start_Search (Search => search, Directory => target_directory, Pattern => pattern, Filter => filter); while DIR.More_Entries (search) loop DIR.Get_Next_Entry (search, dirent); declare SN : constant String := DIR.Simple_Name (dirent); oldfile : constant String := target_directory & "/" & SN; newfile : constant String := source_directory & "/" & SN; begin if DIR.Exists (newfile) then DIR.Copy_File (Source_Name => newfile, Target_Name => oldfile); end if; exception when others => TIO.Put_Line ("Failed to copy " & newfile & " over to " & oldfile); end; end loop; DIR.End_Search (search); end replace_directory_contents; end File_Operations;
Add safeguard for non-existent directory
Add safeguard for non-existent directory procedure: replace_directory_contents
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
0a5841d920429561f52f424f1fe02a9b370d6909
awa/plugins/awa-wikis/src/awa-wikis-beans.adb
awa/plugins/awa-wikis/src/awa-wikis-beans.adb
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body AWA.Wikis.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Wiki_Space_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.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the wiki space. -- ------------------------------ overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Wiki_Space (Bean); end Save; -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Wiki_Space_Bean bean instance. -- ------------------------------ function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Wiki_Space_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Wiki_Page_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.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); elsif Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the wiki page. -- ------------------------------ overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin if Bean.Is_Inserted then Bean.Service.Save (Bean); else Bean.Service.Create_Wiki_Page (Bean.Wiki_Space, Bean); end if; end Save; -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Wiki_Page_Bean bean instance. -- ------------------------------ function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Wiki_Page_Bean_Access := new Wiki_Page_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Wiki_Page_Bean; end AWA.Wikis.Beans;
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services; with AWA.Services.Contexts; package body AWA.Wikis.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Wiki_Space_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.Wikis.Models.Wiki_Space_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the wiki space. -- ------------------------------ overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Service.Save_Wiki_Space (Bean); end Save; -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Wiki_Space_Bean bean instance. -- ------------------------------ function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Wiki_Space_Bean_Access := new Wiki_Space_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Wiki_Space_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Wiki_Page_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.Wikis.Models.Wiki_Page_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); elsif Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the wiki page. -- ------------------------------ overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin if Bean.Is_Inserted then Bean.Service.Save (Bean); else Bean.Service.Create_Wiki_Page (Bean.Wiki_Space, Bean); end if; end Save; -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Wiki_Page_Bean bean instance. -- ------------------------------ function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Wiki_Page_Bean_Access := new Wiki_Page_Bean; begin Object.Service := Module; return Object.all'Access; end Create_Wiki_Page_Bean; -- ------------------------------ -- Load the list of wikis. -- ------------------------------ procedure Load_Wikis (List : in Wiki_Admin_Bean) is use AWA.Wikis.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 := List.Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Wikis.Models.Query_Wiki_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Params => Query, Name => "table", Table => AWA.Wikis.Models.WIKI_SPACE_TABLE, Session => Session); AWA.Wikis.Models.List (List.Wiki_List_Bean.all, Session, Query); List.Flags (INIT_WIKI_LIST) := True; end Load_Wikis; -- ------------------------------ -- Get the wiki space identifier. -- ------------------------------ function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier is use type ADO.Identifier; begin if List.Wiki_Id = ADO.NO_IDENTIFIER then if not List.Flags (INIT_WIKI_LIST) then Load_Wikis (List); end if; if not List.Wiki_List.List.Is_Empty then return List.Wiki_List.List.Element (0).Id; end if; end if; return List.Wiki_Id; end Get_Wiki_Id; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "wikis" then if not List.Init_Flags (INIT_WIKI_LIST) then Load_Wikis (List); end if; return Util.Beans.Objects.To_Object (Value => List.Wiki_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := List.Get_Wiki_Id; begin if Id = ADO.NO_IDENTIFIER then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); end if; end; 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 Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Wiki_Id := ADO.Utils.To_Identifier (Value); end if; end Set_Value; -- ------------------------------ -- Create the Wiki_Admin_Bean bean instance. -- ------------------------------ function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Wiki_Admin_Bean_Access := new Wiki_Admin_Bean; begin Object.Module := Module; Object.Flags := Object.Init_Flags'Access; Object.Wiki_List_Bean := Object.Wiki_List'Access; return Object.all'Access; end Create_Wiki_Admin_Bean; end AWA.Wikis.Beans;
Implement the Wiki_Admin_Bean
Implement the Wiki_Admin_Bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a98d831b13369033943f0dc0040ac1a6b6fdde7a
mat/src/mat-readers-streams-sockets.ads
mat/src/mat-readers-streams-sockets.ads
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Containers.Doubly_Linked_Lists; with Util.Streams.Sockets; with GNAT.Sockets; package MAT.Readers.Streams.Sockets is type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private; -- Initialize the socket listener. overriding procedure Initialize (Listener : in out Socket_Listener_Type); -- Destroy the socket listener. overriding procedure Finalize (Listener : in out Socket_Listener_Type); -- Open the socket to accept connections and start the listener task. procedure Start (Listener : in out Socket_Listener_Type; List : in MAT.Readers.Reader_List_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); -- Stop the listener socket. procedure Stop (Listener : in out Socket_Listener_Type); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type); type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private; type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class; procedure Close (Reader : in out Socket_Reader_Type); private type Socket_Listener_Type_Access is access all Socket_Listener_Type; task type Socket_Listener_Task is entry Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Listener_Task; task type Socket_Reader_Task is entry Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type); end Socket_Reader_Task; type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record Socket : aliased Util.Streams.Sockets.Socket_Stream; Server : Socket_Reader_Task; Client : GNAT.Sockets.Socket_Type; Stop : Boolean := False; end record; package Socket_Client_Lists is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Socket_Reader_Type_Access); type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record List : MAT.Readers.Reader_List_Type_Access; Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; Clients : Socket_Client_Lists.List; end record; end MAT.Readers.Streams.Sockets;
----------------------------------------------------------------------- -- mat-readers-sockets -- Reader for TCP/IP sockets -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Containers.Doubly_Linked_Lists; with Util.Streams.Sockets; with GNAT.Sockets; package MAT.Readers.Streams.Sockets is type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with private; -- Initialize the socket listener. overriding procedure Initialize (Listener : in out Socket_Listener_Type); -- Destroy the socket listener. overriding procedure Finalize (Listener : in out Socket_Listener_Type); -- Open the socket to accept connections and start the listener task. procedure Start (Listener : in out Socket_Listener_Type; List : in MAT.Events.Probes.Reader_List_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); -- Stop the listener socket. procedure Stop (Listener : in out Socket_Listener_Type); -- Create a target instance for the new client. procedure Create_Target (Listener : in out Socket_Listener_Type; Client : in GNAT.Sockets.Socket_Type; Address : in GNAT.Sockets.Sock_Addr_Type); type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private; type Socket_Reader_Type_Access is access all Socket_Reader_Type'Class; procedure Close (Reader : in out Socket_Reader_Type); private type Socket_Listener_Type_Access is access all Socket_Listener_Type; task type Socket_Listener_Task is entry Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type); end Socket_Listener_Task; task type Socket_Reader_Task is entry Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type); end Socket_Reader_Task; type Socket_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record Socket : aliased Util.Streams.Sockets.Socket_Stream; Server : Socket_Reader_Task; Client : GNAT.Sockets.Socket_Type; Stop : Boolean := False; end record; package Socket_Client_Lists is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Socket_Reader_Type_Access); type Socket_Listener_Type is new Ada.Finalization.Limited_Controlled with record List : MAT.Events.Probes.Reader_List_Type_Access; Accept_Selector : aliased GNAT.Sockets.Selector_Type; Listener : Socket_Listener_Task; Clients : Socket_Client_Lists.List; end record; end MAT.Readers.Streams.Sockets;
Fix the Start procedure definition
Fix the Start procedure definition
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6804f84da95924fd4f46ac3bcefa7c72f2d1612f
src/configure.ads
src/configure.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt private with Ada.Characters.Latin_1; private with Parameters; package Configure is menu_error : exception; -- Interactive configuration menu procedure launch_configure_menu; private package LAT renames Ada.Characters.Latin_1; package PM renames Parameters; indent : constant String (1 .. 3) := (others => LAT.Space); type option is range 1 .. 16; type default is range 1 .. 10; subtype ofield is String (1 .. 30); type desc_type is array (option) of ofield; type default_type is array (default) of ofield; descriptions : constant desc_type := ( "[A] System root directory ", "[B] Toolchain directory ", "[C] Localbase directory ", "[D] Conspiracy directory ", "[E] Custom ports directory ", "[F] Distfiles directory ", "[G] Packages directory ", "[H] Compiler cache directory ", "[I] Build base directory ", "[J] Build logs directory ", "[K] Num. concurrent builders ", "[L] Max. jobs per builder ", "[M] Avoid use of tmpfs ", "[N] Always record options ", "[O] Display using ncurses ", "[P] Fetch prebuilt packages " ); version_desc : constant default_type := ( "[A] Firebird SQL server ", "[B] Lua (language) ", "[C] MySQL-workalike server ", "[D] Perl (language) ", "[E] PHP (language) ", "[F] PostgreSQL server ", "[G] Python 3 (language) ", "[H] Ruby (language) ", "[I] SSL/TLS library ", "[J] TCL/TK toolkit " ); optX5A : constant String := "[V] Set version defaults (e.g. perl, ruby, mysql ...)"; optX1A : constant String := "[>] Switch/create profiles (changes discarded)"; optX1B : constant String := "[>] Switch/create profiles"; optX4B : constant String := "[<] Delete alternative profile"; optX2A : constant String := "[ESC] Exit without saving changes"; optX3A : constant String := "[RET] Save changes (starred)"; optX3B : constant String := "[RET] Exit"; dupe : PM.configuration_record; version_A : constant String := "2.5:3.0"; -- Firebird SQL version_B : constant String := "5.2:5.3"; -- Lua version_C : constant String := "oracle-5.5:oracle-5.6:oracle-5.7:" & "mariadb-10.1:mariadb-10.2:" & "percona-5.5:percona-5.6:percona-5.7:" & "galera-5.5:galera-5.6:galera-5.7"; version_D : constant String := "5.22:5.24"; -- Perl version_E : constant String := "5.6:7.0:7.1"; -- php version_F : constant String := "9.2:9.3:9.4:9.5:9.6"; -- postgresql version_G : constant String := "3.5:3.6"; -- python3 version_H : constant String := "2.3:2.4"; -- ruby version_I : constant String := "openssl:openssl-devel:libressl:libressl-devel"; version_J : constant String := "8.5:8.6"; -- TCL/TK procedure clear_screen; procedure print_header; procedure print_opt (opt : option; pristine : in out Boolean); procedure change_directory_option (opt : option; pristine : in out Boolean); procedure change_boolean_option (opt : option; pristine : in out Boolean); procedure change_positive_option (opt : option; pristine : in out Boolean); procedure delete_profile; procedure switch_profile; procedure move_to_defaults_menu (pristine_def : in out Boolean); procedure print_default (def : default; pristine_def : in out Boolean); procedure update_version (def : default; choices : String; label : String); procedure print_menu (pristine : in out Boolean; extra_profiles : Boolean; pristine_def : Boolean); end Configure;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt private with Ada.Characters.Latin_1; private with Parameters; package Configure is menu_error : exception; -- Interactive configuration menu procedure launch_configure_menu; private package LAT renames Ada.Characters.Latin_1; package PM renames Parameters; indent : constant String (1 .. 3) := (others => LAT.Space); type option is range 1 .. 16; type default is range 1 .. 10; subtype ofield is String (1 .. 30); type desc_type is array (option) of ofield; type default_type is array (default) of ofield; descriptions : constant desc_type := ( "[A] System root directory ", "[B] Toolchain directory ", "[C] Localbase directory ", "[D] Conspiracy directory ", "[E] Custom ports directory ", "[F] Distfiles directory ", "[G] Packages directory ", "[H] Compiler cache directory ", "[I] Build base directory ", "[J] Build logs directory ", "[K] Num. concurrent builders ", "[L] Max. jobs per builder ", "[M] Avoid use of tmpfs ", "[N] Always record options ", "[O] Display using ncurses ", "[P] Fetch prebuilt packages " ); version_desc : constant default_type := ( "[A] Firebird SQL server ", "[B] Lua (language) ", "[C] MySQL-workalike server ", "[D] Perl (language) ", "[E] PHP (language) ", "[F] PostgreSQL server ", "[G] Python 3 (language) ", "[H] Ruby (language) ", "[I] SSL/TLS library ", "[J] TCL/TK toolkit " ); optX5A : constant String := "[V] Set version defaults (e.g. perl, ruby, mysql ...)"; optX1A : constant String := "[>] Switch/create profiles (changes discarded)"; optX1B : constant String := "[>] Switch/create profiles"; optX4B : constant String := "[<] Delete alternative profile"; optX2A : constant String := "[ESC] Exit without saving changes"; optX3A : constant String := "[RET] Save changes (starred)"; optX3B : constant String := "[RET] Exit"; dupe : PM.configuration_record; version_A : constant String := "2.5:3.0"; -- Firebird SQL version_B : constant String := "5.2:5.3"; -- Lua version_C : constant String := "oracle-5.5:oracle-5.6:oracle-5.7:" & "mariadb-10.1:mariadb-10.2:" & "percona-5.5:percona-5.6:percona-5.7:" & "galera-5.5:galera-5.6:galera-5.7"; version_D : constant String := "5.22:5.24"; -- Perl version_E : constant String := "5.6:7.0:7.1"; -- php version_F : constant String := "9.2:9.3:9.4:9.5:9.6"; -- postgresql version_G : constant String := "3.4:3.5"; -- python3 version_H : constant String := "2.3:2.4"; -- ruby version_I : constant String := "openssl:openssl-devel:libressl:libressl-devel"; version_J : constant String := "8.5:8.6"; -- TCL/TK procedure clear_screen; procedure print_header; procedure print_opt (opt : option; pristine : in out Boolean); procedure change_directory_option (opt : option; pristine : in out Boolean); procedure change_boolean_option (opt : option; pristine : in out Boolean); procedure change_positive_option (opt : option; pristine : in out Boolean); procedure delete_profile; procedure switch_profile; procedure move_to_defaults_menu (pristine_def : in out Boolean); procedure print_default (def : default; pristine_def : in out Boolean); procedure update_version (def : default; choices : String; label : String); procedure print_menu (pristine : in out Boolean; extra_profiles : Boolean; pristine_def : Boolean); end Configure;
align python options with reality
align python options with reality
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
124f52c21dc6828779cdb1d9c7e1a7a8ad16c772
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with ASF.Helpers.Beans; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Components.Wikis; -- == Wiki Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. -- -- == Ada Beans == -- @include wikis.xml package AWA.Wikis.Beans is use Ada.Strings.Wide_Wide_Unbounded; type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; end record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Wiki_Links_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Wiki_Links_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record -- The wiki module instance. Module : Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read page counter associated with the wiki page. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.WIKI_PAGE_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The wiki page links. Links : aliased Wiki_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_View_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_View_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the information about the wiki page to display it. overriding procedure Load (Bean : in out Wiki_View_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_View_Bean bean instance. function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Wiki_View_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean, Element_Access => Wiki_View_Bean_Access); -- Get a select item list which contains a list of wiki formats. function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Module : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki space information. overriding procedure Load (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Page Bean -- ------------------------------ -- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from -- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member. -- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the -- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether -- we have to create a new version or not. type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Module : Modules.Wiki_Module_Access := null; -- The page content. Content : Models.Wiki_Content_Ref; Has_Content : Boolean := False; Format : AWA.Wikis.Models.Format_Type := AWA.Wikis.Models.FORMAT_CREOLE; New_Content : Ada.Strings.Unbounded.Unbounded_String; New_Comment : Ada.Strings.Unbounded.Unbounded_String; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Returns True if the wiki page has a new text content and requires -- a new version to be created. function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki page. overriding procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Setup the wiki page for the creation. overriding procedure Setup (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki List Bean -- ------------------------------ -- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record Module : Modules.Wiki_Module_Access := null; Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean; Tags : AWA.Tags.Beans.Entity_Tag_Map; Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access; end record; type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Wiki_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of pages. If a tag was set, filter the list of pages with the tag. procedure Load_List (Into : in out Wiki_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Version List Bean -- ------------------------------ type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record Module : Modules.Wiki_Module_Access := null; Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean; Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access; end record; type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Version_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Version_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Into : in out Wiki_Version_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Post_List_Bean bean instance. function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with ASF.Helpers.Beans; with Wiki.Strings; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Components.Wikis; -- == Wiki Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. -- -- == Ada Beans == -- @include wikis.xml package AWA.Wikis.Beans is use Ada.Strings.Wide_Wide_Unbounded; type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; end record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Wiki_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Wiki_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record -- The wiki module instance. Module : Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read page counter associated with the wiki page. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.WIKI_PAGE_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The wiki page links. Links : aliased Wiki_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_View_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_View_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the information about the wiki page to display it. overriding procedure Load (Bean : in out Wiki_View_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_View_Bean bean instance. function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Wiki_View_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean, Element_Access => Wiki_View_Bean_Access); -- Get a select item list which contains a list of wiki formats. function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Module : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki space information. overriding procedure Load (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Page Bean -- ------------------------------ -- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from -- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member. -- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the -- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether -- we have to create a new version or not. type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Module : Modules.Wiki_Module_Access := null; -- The page content. Content : Models.Wiki_Content_Ref; Has_Content : Boolean := False; Format : AWA.Wikis.Models.Format_Type := AWA.Wikis.Models.FORMAT_CREOLE; New_Content : Ada.Strings.Unbounded.Unbounded_String; New_Comment : Ada.Strings.Unbounded.Unbounded_String; Wiki_Space : Wiki_Space_Bean; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Returns True if the wiki page has a new text content and requires -- a new version to be created. function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki page. overriding procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Setup the wiki page for the creation. overriding procedure Setup (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki List Bean -- ------------------------------ -- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record Module : Modules.Wiki_Module_Access := null; Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean; Tags : AWA.Tags.Beans.Entity_Tag_Map; Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access; end record; type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Wiki_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of pages. If a tag was set, filter the list of pages with the tag. procedure Load_List (Into : in out Wiki_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Version List Bean -- ------------------------------ type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record Module : Modules.Wiki_Module_Access := null; Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean; Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access; end record; type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Version_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Version_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Into : in out Wiki_Version_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Post_List_Bean bean instance. function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
Update the wiki link renderer
Update the wiki link renderer
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3dc8b265d0fea46ba131b27f4563e6628a93d652
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. -- function Has_Role (User : in Principal; -- Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- == Discovery: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Verify: acknowledge the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
Remove the Has_Role operation
Remove the Has_Role operation
Ada
apache-2.0
stcarrez/ada-security
d963ba300e2d1822729805e7153413571dac61e6
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 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.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.Mappers; with GNAT.Regexp; with Security.Contexts; -- == URL Security Policy == -- The `Security.Policies.Urls` implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === Policy creation === -- An instance of the `URL_Policy` must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission `create-workspace` or `admin`. -- These two permissions are checked according to another security policy. -- The XML configuration can define several `url-policy`. They are checked in -- the order defined in the XML. In other words, the first `url-policy` that matches -- the URL is used to verify the permission. -- -- The `url-policy` definition can contain several `permission`. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a `URL_Permission` object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Mapper : in out Util.Serialize.Mappers.Processing); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.URLs;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.Mappers; with GNAT.Regexp; with Security.Contexts; -- == URL Security Policy == -- The `Security.Policies.Urls` implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === Policy creation === -- An instance of the `URL_Policy` must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission `create-workspace` or `admin`. -- These two permissions are checked according to another security policy. -- The XML configuration can define several `url-policy`. They are checked in -- the order defined in the XML. In other words, the first `url-policy` that matches -- the URL is used to verify the permission. -- -- The `url-policy` definition can contain several `permission`. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a `URL_Permission` object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Mapper : in out Util.Serialize.Mappers.Processing); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); package Atomic_Rules_Ref is new Rules_Ref.IR.Atomic; type Rules_Ref_Access is access Atomic_Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.URLs;
Update after changes in Util.Refs package
Update after changes in Util.Refs package
Ada
apache-2.0
stcarrez/ada-security
0beee6afef7d0a9849a8727b26f8fec35c5c7736
src/util-serialize-io-form.adb
src/util-serialize-io-form.adb
----------------------------------------------------------------------- -- swagger-streams-forms -- x-www-form-urlencoded streams -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Util.Strings; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.Form is use Ada.Strings.Unbounded; procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access) is begin Stream.Stream := Output; end Initialize; -- ------------------------------ -- Flush the buffer (if any) to the sink. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Stream) is begin Stream.Stream.Flush; end Flush; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Stream) is begin Stream.Stream.Close; end Close; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin Stream.Stream.Write (Buffer); end Write; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; procedure Write_Escape (Stream : in out Output_Stream; Value : in String) is begin for C of Value loop if C = ' ' then Stream.Stream.Write ('+'); elsif C >= 'a' and C <= 'z' then Stream.Stream.Write (C); elsif C >= 'A' and C <= 'Z' then Stream.Stream.Write (C); elsif C >= '0' and C <= '9' then Stream.Stream.Write (C); elsif C = '_' or C = '-' then Stream.Stream.Write (C); else Stream.Stream.Write ('%'); Stream.Stream.Write (Conversion (1 + (Character'Pos (C) / 16))); Stream.Stream.Write (Conversion (1 + (Character'Pos (C) mod 16))); end if; end loop; end Write_Escape; -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Write_Escape (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Write_Escape (Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Value)); end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Stream.Write (Util.Strings.Image (Value)); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Stream.Write (if Value then "true" else "false"); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is begin null; end Write_Null_Attribute; -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin Stream.Write_Wide_Attribute (Name, Value); end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin null; end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin null; end Write_Enum_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is begin null; end Write_Null_Entity; -- ------------------------------ -- Parse the stream using the form parser. -- ------------------------------ procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class) is function From_Hex (C : in Character) return Natural; procedure Parse_Token (Into : out Ada.Strings.Unbounded.Unbounded_String); Name : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; Last : Character; function From_Hex (C : in Character) return Natural is begin if C >= 'a' and C <= 'f' then return Character'Pos (C) - Character'Pos ('a') + 10; elsif C >= 'A' and C <= 'F' then return Character'Pos (C) - Character'Pos ('A') + 10; elsif C >= '0' and C <= '9' then return Character'Pos (C) - Character'Pos ('0'); else raise Parse_Error with "Invalid hexadecimal character: " & C; end if; end From_Hex; procedure Parse_Token (Into : out Ada.Strings.Unbounded.Unbounded_String) is C1, C2 : Character; begin Into := Ada.Strings.Unbounded.Null_Unbounded_String; loop Stream.Read (C1); if C1 = '&' or C1 = '=' then Last := C1; return; end if; if C1 = '+' then Ada.Strings.Unbounded.Append (Into, ' '); elsif C1 = '%' then Stream.Read (C1); Stream.Read (C2); Ada.Strings.Unbounded.Append (Into, Character'Val ((16 * From_Hex (C1)) + From_Hex (C2))); else Ada.Strings.Unbounded.Append (Into, C1); end if; end loop; end Parse_Token; begin Sink.Start_Object ("", Handler); loop Parse_Token (Name); if Last /= '=' then raise Parse_Error with "Missing '=' after parameter name"; end if; Parse_Token (Value); Sink.Set_Member (To_String (Name), Util.Beans.Objects.To_Object (Value), Handler); end loop; exception when Ada.IO_Exceptions.Data_Error => Sink.Finish_Object ("", Handler); return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return ""; end Get_Location; -- ------------------------------ -- Read a form file and return an object. -- ------------------------------ function Read (Path : in String) return Util.Beans.Objects.Object is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse (Path, R); return R.Get_Root; end Read; end Util.Serialize.IO.Form;
----------------------------------------------------------------------- -- swagger-streams-forms -- x-www-form-urlencoded streams -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Util.Strings; with Util.Beans.Objects.Readers; package body Util.Serialize.IO.Form is use Ada.Strings.Unbounded; procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access) is begin Stream.Stream := Output; end Initialize; -- ------------------------------ -- Flush the buffer (if any) to the sink. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Stream) is begin Stream.Stream.Flush; end Flush; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Stream) is begin Stream.Stream.Close; end Close; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin Stream.Stream.Write (Buffer); end Write; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; procedure Write_Escape (Stream : in out Output_Stream; Value : in String) is begin for C of Value loop if C = ' ' then Stream.Stream.Write ('+'); elsif C >= 'a' and C <= 'z' then Stream.Stream.Write (C); elsif C >= 'A' and C <= 'Z' then Stream.Stream.Write (C); elsif C >= '0' and C <= '9' then Stream.Stream.Write (C); elsif C = '_' or C = '-' then Stream.Stream.Write (C); else Stream.Stream.Write ('%'); Stream.Stream.Write (Conversion (1 + (Character'Pos (C) / 16))); Stream.Stream.Write (Conversion (1 + (Character'Pos (C) mod 16))); end if; end loop; end Write_Escape; -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Write_Escape (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Write_Escape (Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Value)); end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Stream.Write (Util.Strings.Image (Value)); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin if Stream.Has_Param then Stream.Stream.Write ('&'); end if; Stream.Has_Param := True; Stream.Write_Escape (Name); Stream.Stream.Write ('='); Stream.Stream.Write (if Value then "true" else "false"); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Attribute; -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is begin null; end Write_Null_Attribute; -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin Stream.Write_Wide_Attribute (Name, Value); end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is begin Stream.Write_Attribute (Name, Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin null; end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin null; end Write_Enum_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Write_Entity; -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is begin null; end Write_Null_Entity; -- ------------------------------ -- Parse the stream using the form parser. -- ------------------------------ procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class) is function From_Hex (C : in Character) return Natural; procedure Parse_Token (Into : out Ada.Strings.Unbounded.Unbounded_String); Name : Ada.Strings.Unbounded.Unbounded_String; Value : Ada.Strings.Unbounded.Unbounded_String; Last : Character; function From_Hex (C : in Character) return Natural is begin if C >= 'a' and C <= 'f' then return Character'Pos (C) - Character'Pos ('a') + 10; elsif C >= 'A' and C <= 'F' then return Character'Pos (C) - Character'Pos ('A') + 10; elsif C >= '0' and C <= '9' then return Character'Pos (C) - Character'Pos ('0'); else raise Parse_Error with "Invalid hexadecimal character: " & C; end if; end From_Hex; procedure Parse_Token (Into : out Ada.Strings.Unbounded.Unbounded_String) is C1, C2 : Character; begin Into := Ada.Strings.Unbounded.Null_Unbounded_String; loop Stream.Read (C1); if C1 = '&' or C1 = '=' then Last := C1; return; end if; if C1 = '+' then Ada.Strings.Unbounded.Append (Into, ' '); elsif C1 = '%' then Stream.Read (C1); Stream.Read (C2); Ada.Strings.Unbounded.Append (Into, Character'Val ((16 * From_Hex (C1)) + From_Hex (C2))); else Ada.Strings.Unbounded.Append (Into, C1); end if; end loop; exception when Ada.IO_Exceptions.Data_Error => return; end Parse_Token; begin Sink.Start_Object ("", Handler); loop Parse_Token (Name); if Last /= '=' then raise Parse_Error with "Missing '=' after parameter name"; end if; Parse_Token (Value); Sink.Set_Member (To_String (Name), Util.Beans.Objects.To_Object (Value), Handler); if Stream.Is_Eof then Sink.Finish_Object ("", Handler); return; end if; if Last /= '&' then raise Parse_Error with "Missing '&' after parameter value"; end if; end loop; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ function Get_Location (Handler : in Parser) return String is begin return ""; end Get_Location; -- ------------------------------ -- Read a form file and return an object. -- ------------------------------ function Read (Path : in String) return Util.Beans.Objects.Object is P : Parser; R : Util.Beans.Objects.Readers.Reader; begin P.Parse (Path, R); return R.Get_Root; end Read; end Util.Serialize.IO.Form;
Fix Parse procedure to detect errors and end of stream
Fix Parse procedure to detect errors and end of stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5097675bf634f3d8478167a68772fd41a90a8bf1
awa/src/awa-commands.ads
awa/src/awa-commands.ads
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- 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 Ada.Finalization; with Util.Commands; with AWA.Applications; private with Keystore.Passwords; private with Keystore.Passwords.GPG; private with Util.Commands.Consoles.Text; private with ASF.Applications; private with AWA.Applications.Factory; private with Keystore.Properties; private with Keystore.Files; private with Keystore.Passwords.Keys; private with GNAT.Command_Line; private with GNAT.Strings; package AWA.Commands is Error : exception; FILL_CONFIG : constant String := "fill-mode"; GPG_CRYPT_CONFIG : constant String := "gpg-encrypt"; GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt"; GPG_LIST_CONFIG : constant String := "gpg-list-keys"; subtype Argument_List is Util.Commands.Argument_List; type Context_Type is limited new Ada.Finalization.Limited_Controlled with private; overriding procedure Initialize (Context : in out Context_Type); overriding procedure Finalize (Context : in out Context_Type); -- Returns True if a keystore is used by the configuration and must be unlocked. function Use_Keystore (Context : in Context_Type) return Boolean; -- Open the keystore file using the password password. procedure Open_Keystore (Context : in out Context_Type); -- Get the keystore file path. function Get_Keystore_Path (Context : in out Context_Type) return String; -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type); private function "-" (Message : in String) return String is (Message); procedure Load_Configuration (Context : in out Context_Type); package GC renames GNAT.Command_Line; type Field_Number is range 1 .. 256; type Notice_Type is (N_USAGE, N_INFO, N_ERROR); package Consoles is new Util.Commands.Consoles (Field_Type => Field_Number, Notice_Type => Notice_Type); package Text_Consoles is new Consoles.Text; subtype Justify_Type is Consoles.Justify_Type; type Context_Type is limited new Ada.Finalization.Limited_Controlled with record Console : Text_Consoles.Console_Type; Wallet : aliased Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Config : Keystore.Wallet_Config := Keystore.Secure_Config; Secure_Config : Keystore.Properties.Manager; App_Config : ASF.Applications.Config; File_Config : ASF.Applications.Config; Factory : AWA.Applications.Factory.Application_Factory; Provider : Keystore.Passwords.Provider_Access; Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access; Slot : Keystore.Key_Slot; Version : aliased Boolean := False; Verbose : aliased Boolean := False; Debug : aliased Boolean := False; Dump : aliased Boolean := False; Zero : aliased Boolean := False; Config_File : aliased GNAT.Strings.String_Access; Wallet_File : aliased GNAT.Strings.String_Access; Data_Path : aliased GNAT.Strings.String_Access; Wallet_Key_File : aliased GNAT.Strings.String_Access; Password_File : aliased GNAT.Strings.String_Access; Password_Env : aliased GNAT.Strings.String_Access; Unsafe_Password : aliased GNAT.Strings.String_Access; Password_Socket : aliased GNAT.Strings.String_Access; Password_Command : aliased GNAT.Strings.String_Access; Password_Askpass : aliased Boolean := False; No_Password_Opt : Boolean := False; Command_Config : GC.Command_Line_Configuration; First_Arg : Positive := 1; GPG : Keystore.Passwords.GPG.Context_Type; end record; procedure Setup_Password_Provider (Context : in out Context_Type); procedure Setup_Key_Provider (Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type); function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer with Import => True, Convention => C, Link_Name => "daemon"; pragma Weak_External (Sys_Daemon); end AWA.Commands;
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- 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 Ada.Finalization; with Util.Commands; with AWA.Applications; with Ada.Exceptions; private with Keystore.Passwords; private with Keystore.Passwords.GPG; private with Util.Commands.Consoles.Text; private with ASF.Applications; private with AWA.Applications.Factory; private with Keystore.Properties; private with Keystore.Files; private with Keystore.Passwords.Keys; private with GNAT.Command_Line; private with GNAT.Strings; package AWA.Commands is Error : exception; FILL_CONFIG : constant String := "fill-mode"; GPG_CRYPT_CONFIG : constant String := "gpg-encrypt"; GPG_DECRYPT_CONFIG : constant String := "gpg-decrypt"; GPG_LIST_CONFIG : constant String := "gpg-list-keys"; subtype Argument_List is Util.Commands.Argument_List; type Context_Type is limited new Ada.Finalization.Limited_Controlled with private; overriding procedure Initialize (Context : in out Context_Type); overriding procedure Finalize (Context : in out Context_Type); -- Returns True if a keystore is used by the configuration and must be unlocked. function Use_Keystore (Context : in Context_Type) return Boolean; -- Open the keystore file using the password password. procedure Open_Keystore (Context : in out Context_Type); -- Get the keystore file path. function Get_Keystore_Path (Context : in out Context_Type) return String; -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type); procedure Print (Context : in out Context_Type; Ex : in Ada.Exceptions.Exception_Occurrence); private function "-" (Message : in String) return String is (Message); procedure Load_Configuration (Context : in out Context_Type; Path : in String); package GC renames GNAT.Command_Line; type Field_Number is range 1 .. 256; type Notice_Type is (N_USAGE, N_INFO, N_ERROR); package Consoles is new Util.Commands.Consoles (Field_Type => Field_Number, Notice_Type => Notice_Type); package Text_Consoles is new Consoles.Text; subtype Justify_Type is Consoles.Justify_Type; type Context_Type is limited new Ada.Finalization.Limited_Controlled with record Console : Text_Consoles.Console_Type; Wallet : aliased Keystore.Files.Wallet_File; Info : Keystore.Wallet_Info; Config : Keystore.Wallet_Config := Keystore.Secure_Config; Secure_Config : Keystore.Properties.Manager; App_Config : ASF.Applications.Config; File_Config : ASF.Applications.Config; Factory : AWA.Applications.Factory.Application_Factory; Provider : Keystore.Passwords.Provider_Access; Key_Provider : Keystore.Passwords.Keys.Key_Provider_Access; Slot : Keystore.Key_Slot; Version : aliased Boolean := False; Verbose : aliased Boolean := False; Debug : aliased Boolean := False; Dump : aliased Boolean := False; Zero : aliased Boolean := False; Config_File : aliased GNAT.Strings.String_Access; Wallet_File : aliased GNAT.Strings.String_Access; Data_Path : aliased GNAT.Strings.String_Access; Wallet_Key_File : aliased GNAT.Strings.String_Access; Password_File : aliased GNAT.Strings.String_Access; Password_Env : aliased GNAT.Strings.String_Access; Unsafe_Password : aliased GNAT.Strings.String_Access; Password_Socket : aliased GNAT.Strings.String_Access; Password_Command : aliased GNAT.Strings.String_Access; Password_Askpass : aliased Boolean := False; No_Password_Opt : Boolean := False; Command_Config : GC.Command_Line_Configuration; First_Arg : Positive := 1; GPG : Keystore.Passwords.GPG.Context_Type; end record; procedure Setup_Password_Provider (Context : in out Context_Type); procedure Setup_Key_Provider (Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type); function Sys_Daemon (No_Chdir : in Integer; No_Close : in Integer) return Integer with Import => True, Convention => C, Link_Name => "daemon"; pragma Weak_External (Sys_Daemon); end AWA.Commands;
Update Load_Configuration to add a Path parameter Add Print procedure to analyze an exception and report an error message
Update Load_Configuration to add a Path parameter Add Print procedure to analyze an exception and report an error message
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b44ac7f38aa13c60b516eef01d5b3127682c4471
src/asf-views.adb
src/asf-views.adb
----------------------------------------------------------------------- -- asf-views -- Views -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ASF.Views is -- ------------------------------ -- Source line information -- ------------------------------ -- ------------------------------ -- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b> -- and whose relative path portion starts at <b>Relative_Position</b>. -- ------------------------------ function Create_File_Info (Path : in String; Relative_Position : in Natural) return File_Info_Access is begin return new File_Info '(Length => Path'Length, Path => Path, Relative_Pos => Relative_Position); end Create_File_Info; -- ------------------------------ -- Get the relative path name -- ------------------------------ function Relative_Path (File : in File_Info) return String is begin return File.Path (File.Relative_Pos .. File.Path'Last); end Relative_Path; -- ------------------------------ -- Get the line number -- ------------------------------ function Line (Info : Line_Info) return Natural is begin return Info.Line; end Line; -- ------------------------------ -- Get the source file -- ------------------------------ function File (Info : Line_Info) return String is begin return Info.File.Path; end File; end ASF.Views;
----------------------------------------------------------------------- -- asf-views -- Views -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ASF.Views is -- ------------------------------ -- Source line information -- ------------------------------ -- ------------------------------ -- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b> -- and whose relative path portion starts at <b>Relative_Position</b>. -- ------------------------------ function Create_File_Info (Path : in String; Relative_Position : in Natural) return File_Info_Access is begin return new File_Info '(Length => Path'Length, Path => Path, Relative_Pos => Relative_Position - Path'First + 1); end Create_File_Info; -- ------------------------------ -- Get the relative path name -- ------------------------------ function Relative_Path (File : in File_Info) return String is begin return File.Path (File.Relative_Pos .. File.Path'Last); end Relative_Path; -- ------------------------------ -- Get the line number -- ------------------------------ function Line (Info : Line_Info) return Natural is begin return Info.Line; end Line; -- ------------------------------ -- Get the source file -- ------------------------------ function File (Info : Line_Info) return String is begin return Info.File.Path; end File; end ASF.Views;
Fix the Create_File_Info procedure
Fix the Create_File_Info procedure
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8b013f14512f843d51c9015365fd9c0e9fd391d0
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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; Bean : Util.Beans.Objects.Object; -- 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; Parent_Name : Unbounded_String; 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); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_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; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); 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, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.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; Bean : Util.Beans.Objects.Object; -- 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; Parent_Name : Unbounded_String; 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; -- Whether the bean type is a limited type or not. Is_Limited : 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); -- Create an operation with the given name and add it to the table. procedure Add_Operation (Table : in out Table_Definition; Name : in Unbounded_String; Operation : out Model.Operations.Operation_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; package Table_List is new Gen.Model.List (T => Definition, T_Access => Definition_Access); private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Add a Is_Limited boolean property on each table (bean)
Add a Is_Limited boolean property on each table (bean)
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
eed164d412ecbe8cb5463470845557d0a9257e08
awa/plugins/awa-comments/src/awa-comments-modules.adb
awa/plugins/awa-comments/src/awa-comments-modules.adb
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Setup the resource bundles. -- Plugin.Manager := Plugin.Create_User_Manager; -- Register.Register (Plugin => Plugin, -- Name => "AWA.Users.Beans.Authenticate_Bean", -- Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; end AWA.Comments.Modules;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- Create a new comment for the associated database entity. procedure Create_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; end AWA.Comments.Modules;
Implement the Create_Comment and Load_Comment operations
Implement the Create_Comment and Load_Comment operations
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
85e2b87268774c4ddd92acbfb7570dcebad88a9c
src/yaml.ads
src/yaml.ads
private with Ada.Finalization; private with Interfaces; private with Interfaces.C; private with Interfaces.C.Pointers; private with System; package YAML is type UTF8_String is new String; type Document_Type is tagged limited private; -- Holder for a YAML document type Node_Kind is (No_Node, -- An empty node Scalar_Node, -- A scalar node Sequence_Node, -- A sequence node Mapping_Node -- A mapping node ) with Convention => C; -- Type of a node in a document type Node_Ref is tagged private; -- Reference to a node as part of a document. Such values must not outlive -- the value for the document that owns them. No_Node_Ref : constant Node_Ref; function Root_Node (Document : Document_Type'Class) return Node_Ref; -- Return the root node of a document, or No_Node_Ref for an empty -- document. function Kind (Node : Node_Ref) return Node_Kind; -- Return the type of a node function Value (Node : Node_Ref) return UTF8_String with Pre => Kind (Node) = Scalar_Node; function Length (Node : Node_Ref) return Natural with Pre => Kind (Node) in Sequence_Node | Mapping_Node; -- Return the number of items in the Node sequence/mapping function Item (Node : Node_Ref; Index : Positive) return Node_Ref with Pre => Kind (Node) = Sequence_Node and then Index <= Length (Node); -- Return the Index'th item in Node. Index is 1-based. type Node_Pair is record Key, Value : Node_Ref; end record; -- Key/value asssociation in a mapping node function Item (Node : Node_Ref; Index : Positive) return Node_Pair with Pre => Kind (Node) = Mapping_Node and then Index <= Length (Node); -- Return the Index'th key/value association in Node. Index is 1-based. function Item (Node : Node_Ref; Key : UTF8_String) return Node_Ref with Pre => Kind (Node) = Mapping_Node; -- Look for Key in the Node mapping. If there is one, return the -- corresponding Value. Return No_Node_Ref otherwise. type Parser_Type is tagged limited private; -- YAML document parser type Encoding_Type is (Any_Encoding, -- Let the parser choose the encoding UTF8_Encoding, -- The default UTF-8 encoding UTF16LE_Encoding, -- The UTF-16-LE encoding with BOM UTF16BE_Encoding -- The UTF-16-BE encoding with BOM ) with Convention => C; -- Stream encoding procedure Set_Input_String (Parser : in out Parser_Type'Class; Input : String; Encoding : Encoding_Type); -- Set a string input. This maintains a copy of Input in Parser. File_Error : exception; -- Exception raised when file-related errors occurs. For instance: cannot -- open a file, cannot read a file, etc. procedure Set_Input_File (Parser : in out Parser_Type'Class; Filename : String; Encoding : Encoding_Type); -- Set a file input. This opens Filename until the parser is destroyed or -- until another Set_Input_* procedure is successfuly called. If an error -- occurs while opening the file, raise a File_Error and leave the parser -- unmodified. function Load (Parser : in out Parser_Type'Class) return Document_Type; -- Parse the input stream and produce the next YAML document. -- -- Call this function subsequently to produce a sequence of documents -- constituting the input stream. If the produced document has no root -- node, it means that the document end has been reached. -- -- TODO: error handling private subtype C_Int is Interfaces.C.int; subtype C_Index is C_Int range 0 .. C_Int'Last; subtype C_Ptr_Diff is Interfaces.C.ptrdiff_t; type C_Char_Array is array (C_Index) of Interfaces.Unsigned_8; type C_Char_Access is access all C_Char_Array; type C_Node_T; type C_Node_Access is access all C_Node_T; type C_Scalar_Style_T is (Any_Scalar_Style, Plain_Scalar_Style, Single_Quoted_Scalar_Style, Double_Quoted_Scalar_Style, Literal_Scalar_Style, Folded_Scalar_Style) with Convention => C; -- Scalar styles type C_Sequence_Style_T is (Any_Sequence_Style, Block_Sequence_Style, Flow_Sequence_Style) with Convention => C; -- Sequence styles type C_Mapping_Style_T is (Any_Mapping_Style, Block_Mapping_Style, Flow_Mapping_Style) with Convention => C; -- Mapping styles type C_Mark_T is record Index, Line, Column : Interfaces.C.size_t; end record with Convention => C_Pass_By_Copy; -- The pointer position type C_Version_Directive_T is record Major, Minor : C_Int; -- Major and minor version numbers end record with Convention => C_Pass_By_Copy; -- The version directive data type C_Version_Directive_Access is access all C_Version_Directive_T; type C_Tag_Directive_T is record Handle : C_Char_Access; -- The tag handle Prefix : C_Char_Access; -- The tag prefix end record with Convention => C_Pass_By_Copy; -- The tag directive data type C_Tag_Directive_Access is access C_Tag_Directive_T; subtype C_Node_Item_T is C_Int; type C_Node_Item_Array is array (C_Index range <>) of aliased C_Node_Item_T; package C_Node_Item_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Item_T, Element_Array => C_Node_Item_Array, Default_Terminator => -1); subtype C_Node_Item_Access is C_Node_Item_Accesses.Pointer; type C_Node_Pair_T is record Key, Value : C_Int; end record with Convention => C_Pass_By_Copy; type C_Node_Pair_Array is array (C_Index range <>) of aliased C_Node_Pair_T; package C_Node_Pair_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Pair_T, Element_Array => C_Node_Pair_Array, Default_Terminator => (-1, -1)); subtype C_Node_Pair_Access is C_Node_Pair_Accesses.Pointer; ---------------------------- -- Node structure binding -- ---------------------------- type C_Scalar_Node_Data is record Value : C_Char_Access; -- The scalar value Length : Interfaces.C.size_t; -- The length of the scalar value Style : C_Scalar_Style_T; -- The scalar style end record with Convention => C_Pass_By_Copy; type C_Sequence_Items is record Seq_Start, Seq_End, Seq_Top : C_Node_Item_Access; end record with Convention => C_Pass_By_Copy; type C_Sequence_Node_Data is record Items : C_Sequence_Items; -- The stack of sequence items Style : C_Sequence_Style_T; -- The sequence style end record with Convention => C_Pass_By_Copy; type C_Mapping_Pairs is record Map_Start, Map_End, Map_Top : C_Node_Pair_Access; end record with Convention => C_Pass_By_Copy; type C_Mapping_Node_Data is record Pairs : C_Mapping_Pairs; -- The stack of mapping pairs Style : C_Mapping_Style_T; -- The mapping style end record with Convention => C_Pass_By_Copy; type C_Node_Data (Dummy : Node_Kind := No_Node) is record case Dummy is when No_Node => null; when Scalar_Node => Scalar : C_Scalar_Node_Data; -- The scalar parameters (for Scalar_Node) when Sequence_Node => Sequence : C_Sequence_Node_Data; -- The sequence parameters (for Sequence_Node) when Mapping_Node => Mapping : C_Mapping_Node_Data; -- The mapping parameters (for Mapping_Node) end case; end record with Convention => C_Pass_By_Copy, Unchecked_Union; type C_Node_T is record Kind : Node_Kind; -- The node type Tag : C_Char_Access; -- The node tag Data : C_Node_Data; -- The node data Start_Mark, End_Mark : C_Mark_T; end record with Convention => C_Pass_By_Copy; -------------------------------- -- Document structure binding -- -------------------------------- type C_Document_Nodes is record Start_Node, End_Node, Top_Node : C_Node_T; -- Begining, end and top of the stack end record with Convention => C_Pass_By_Copy; type C_Tag_Directives is record Start_Dir, End_Dir : C_Tag_Directive_Access; -- Beginning and end of the tag directives list end record with Convention => C_Pass_By_Copy; type C_Document_T is record Nodes : C_Document_Nodes; -- The document nodes Version_Directives : C_Version_Directive_Access; -- The version directive Tag_Directives : C_Tag_Directives; -- The list of tag directives Start_Implicit, End_Implicit : C_Int; -- Is the document start/end indicator explicit? Start_Mark, End_Mark : C_Mark_T; -- Beginning and end of the document end record with Convention => C_Pass_By_Copy; -- The document structure type C_Document_Access is access all C_Document_T; ------------------------- -- High-level Wrappers -- ------------------------- type Document_Type is limited new Ada.Finalization.Limited_Controlled with record C_Doc : aliased C_Document_T; To_Delete : Boolean; end record; overriding procedure Initialize (Document : in out Document_Type); overriding procedure Finalize (Document : in out Document_Type); type Document_Access is access all Document_Type'Class; type Node_Ref is tagged record Node : C_Node_Access; -- The referenced node Document : Document_Access; -- The document it belongs to end record; No_Node_Ref : constant Node_Ref := (null, null); type C_Parser_Access is new System.Address; type String_Access is access String; type C_File_Ptr is new System.Address; No_File_Ptr : constant C_File_Ptr := C_File_Ptr (System.Null_Address); type Parser_Type is limited new Ada.Finalization.Limited_Controlled with record C_Parser : C_Parser_Access; Input_Encoding : Encoding_Type; Input_String : String_Access; Input_File : C_File_Ptr; end record; overriding procedure Initialize (Parser : in out Parser_Type); overriding procedure Finalize (Parser : in out Parser_Type); end YAML;
private with Ada.Finalization; private with Interfaces; private with Interfaces.C; private with Interfaces.C.Pointers; private with System; package YAML is type UTF8_String is new String; type Document_Type is tagged limited private; -- Holder for a YAML document type Node_Kind is (No_Node, -- An empty node Scalar_Node, -- A scalar node Sequence_Node, -- A sequence node Mapping_Node -- A mapping node ) with Convention => C; -- Type of a node in a document type Node_Ref is tagged private; -- Reference to a node as part of a document. Such values must not outlive -- the value for the document that owns them. No_Node_Ref : constant Node_Ref; function Root_Node (Document : Document_Type'Class) return Node_Ref; -- Return the root node of a document, or No_Node_Ref for an empty -- document. function Kind (Node : Node_Ref) return Node_Kind; -- Return the type of a node function Value (Node : Node_Ref) return UTF8_String with Pre => Kind (Node) = Scalar_Node; function Length (Node : Node_Ref) return Natural with Pre => Kind (Node) in Sequence_Node | Mapping_Node; -- Return the number of items in the Node sequence/mapping function Item (Node : Node_Ref; Index : Positive) return Node_Ref with Pre => Kind (Node) = Sequence_Node and then Index <= Length (Node); -- Return the Index'th item in Node. Index is 1-based. type Node_Pair is record Key, Value : Node_Ref; end record; -- Key/value asssociation in a mapping node function Item (Node : Node_Ref; Index : Positive) return Node_Pair with Pre => Kind (Node) = Mapping_Node and then Index <= Length (Node); -- Return the Index'th key/value association in Node. Index is 1-based. function Item (Node : Node_Ref; Key : UTF8_String) return Node_Ref with Pre => Kind (Node) = Mapping_Node; -- Look for Key in the Node mapping. If there is one, return the -- corresponding Value. Return No_Node_Ref otherwise. type Parser_Type is tagged limited private; -- YAML document parser type Encoding_Type is (Any_Encoding, -- Let the parser choose the encoding UTF8_Encoding, -- The default UTF-8 encoding UTF16LE_Encoding, -- The UTF-16-LE encoding with BOM UTF16BE_Encoding -- The UTF-16-BE encoding with BOM ) with Convention => C; -- Stream encoding procedure Set_Input_String (Parser : in out Parser_Type'Class; Input : String; Encoding : Encoding_Type); -- Set a string input. This maintains a copy of Input in Parser. File_Error : exception; -- Exception raised when file-related errors occurs. For instance: cannot -- open a file, cannot read a file, etc. procedure Set_Input_File (Parser : in out Parser_Type'Class; Filename : String; Encoding : Encoding_Type); -- Set a file input. This opens Filename until the parser is destroyed or -- until another Set_Input_* procedure is successfuly called. If an error -- occurs while opening the file, raise a File_Error and leave the parser -- unmodified. function Load (Parser : in out Parser_Type'Class) return Document_Type; -- Parse the input stream and produce the next YAML document. -- -- Call this function subsequently to produce a sequence of documents -- constituting the input stream. If the produced document has no root -- node, it means that the document end has been reached. -- -- TODO: error handling private subtype C_Int is Interfaces.C.int; subtype C_Index is C_Int range 0 .. C_Int'Last; subtype C_Ptr_Diff is Interfaces.C.ptrdiff_t; type C_Char_Array is array (C_Index) of Interfaces.Unsigned_8; type C_Char_Access is access all C_Char_Array; type C_Node_T; type C_Node_Access is access all C_Node_T; type C_Scalar_Style_T is (Any_Scalar_Style, Plain_Scalar_Style, Single_Quoted_Scalar_Style, Double_Quoted_Scalar_Style, Literal_Scalar_Style, Folded_Scalar_Style) with Convention => C; -- Scalar styles type C_Sequence_Style_T is (Any_Sequence_Style, Block_Sequence_Style, Flow_Sequence_Style) with Convention => C; -- Sequence styles type C_Mapping_Style_T is (Any_Mapping_Style, Block_Mapping_Style, Flow_Mapping_Style) with Convention => C; -- Mapping styles type C_Mark_T is record Index, Line, Column : Interfaces.C.size_t; end record with Convention => C_Pass_By_Copy; -- The pointer position type C_Version_Directive_T is record Major, Minor : C_Int; -- Major and minor version numbers end record with Convention => C_Pass_By_Copy; -- The version directive data type C_Version_Directive_Access is access all C_Version_Directive_T; type C_Tag_Directive_T is record Handle : C_Char_Access; -- The tag handle Prefix : C_Char_Access; -- The tag prefix end record with Convention => C_Pass_By_Copy; -- The tag directive data type C_Tag_Directive_Access is access C_Tag_Directive_T; subtype C_Node_Item_T is C_Int; type C_Node_Item_Array is array (C_Index range <>) of aliased C_Node_Item_T; package C_Node_Item_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Item_T, Element_Array => C_Node_Item_Array, Default_Terminator => -1); subtype C_Node_Item_Access is C_Node_Item_Accesses.Pointer; type C_Node_Pair_T is record Key, Value : C_Int; end record with Convention => C_Pass_By_Copy; type C_Node_Pair_Array is array (C_Index range <>) of aliased C_Node_Pair_T; package C_Node_Pair_Accesses is new Interfaces.C.Pointers (Index => C_Index, Element => C_Node_Pair_T, Element_Array => C_Node_Pair_Array, Default_Terminator => (-1, -1)); subtype C_Node_Pair_Access is C_Node_Pair_Accesses.Pointer; ---------------------------- -- Node structure binding -- ---------------------------- type C_Scalar_Node_Data is record Value : C_Char_Access; -- The scalar value Length : Interfaces.C.size_t; -- The length of the scalar value Style : C_Scalar_Style_T; -- The scalar style end record with Convention => C_Pass_By_Copy; type C_Sequence_Items is record Seq_Start, Seq_End, Seq_Top : C_Node_Item_Access; end record with Convention => C_Pass_By_Copy; type C_Sequence_Node_Data is record Items : C_Sequence_Items; -- The stack of sequence items Style : C_Sequence_Style_T; -- The sequence style end record with Convention => C_Pass_By_Copy; type C_Mapping_Pairs is record Map_Start, Map_End, Map_Top : C_Node_Pair_Access; end record with Convention => C_Pass_By_Copy; type C_Mapping_Node_Data is record Pairs : C_Mapping_Pairs; -- The stack of mapping pairs Style : C_Mapping_Style_T; -- The mapping style end record with Convention => C_Pass_By_Copy; type C_Node_Data (Dummy : Node_Kind := No_Node) is record case Dummy is when No_Node => null; when Scalar_Node => Scalar : C_Scalar_Node_Data; -- The scalar parameters (for Scalar_Node) when Sequence_Node => Sequence : C_Sequence_Node_Data; -- The sequence parameters (for Sequence_Node) when Mapping_Node => Mapping : C_Mapping_Node_Data; -- The mapping parameters (for Mapping_Node) end case; end record with Convention => C_Pass_By_Copy, Unchecked_Union; type C_Node_T is record Kind : Node_Kind; -- The node type Tag : C_Char_Access; -- The node tag Data : C_Node_Data; -- The node data Start_Mark, End_Mark : C_Mark_T; end record with Convention => C_Pass_By_Copy; -------------------------------- -- Document structure binding -- -------------------------------- type C_Document_Nodes is record Start_Node, End_Node, Top_Node : C_Node_T; -- Begining, end and top of the stack end record with Convention => C_Pass_By_Copy; type C_Tag_Directives is record Start_Dir, End_Dir : C_Tag_Directive_Access; -- Beginning and end of the tag directives list end record with Convention => C_Pass_By_Copy; type C_Document_T is record Nodes : C_Document_Nodes; -- The document nodes Version_Directives : C_Version_Directive_Access; -- The version directive Tag_Directives : C_Tag_Directives; -- The list of tag directives Start_Implicit, End_Implicit : C_Int; -- Is the document start/end indicator explicit? Start_Mark, End_Mark : C_Mark_T; -- Beginning and end of the document end record with Convention => C_Pass_By_Copy; -- The document structure type C_Document_Access is access all C_Document_T; ------------------------- -- High-level Wrappers -- ------------------------- type Document_Type is limited new Ada.Finalization.Limited_Controlled with record C_Doc : aliased C_Document_T; -- Inlined C document structure. This is the reason Document_Type is -- limited. To_Delete : Boolean; -- Whether C_Doc has been initialized. In this case, it must be deleted -- during finalization. end record; overriding procedure Initialize (Document : in out Document_Type); overriding procedure Finalize (Document : in out Document_Type); type Document_Access is access all Document_Type'Class; type Node_Ref is tagged record Node : C_Node_Access; -- The referenced node Document : Document_Access; -- The document it belongs to end record; No_Node_Ref : constant Node_Ref := (null, null); type C_Parser_Access is new System.Address; type String_Access is access String; type C_File_Ptr is new System.Address; No_File_Ptr : constant C_File_Ptr := C_File_Ptr (System.Null_Address); type Parser_Type is limited new Ada.Finalization.Limited_Controlled with record C_Parser : C_Parser_Access; Input_Encoding : Encoding_Type; Input_String : String_Access; Input_File : C_File_Ptr; end record; overriding procedure Initialize (Parser : in out Parser_Type); overriding procedure Finalize (Parser : in out Parser_Type); end YAML;
Comment Document_Type's private fields
Comment Document_Type's private fields
Ada
mit
pmderodat/libyaml-ada,pmderodat/libyaml-ada
6500568b2bc2ed0aee894a399841537d8a22bf49
src/wiki.ads
src/wiki.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016, 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. ----------------------------------------------------------------------- -- = Wiki = -- The Wiki engine parses a Wiki text in several Wiki syntax such as `MediaWiki`, -- `Creole`, `Markdown`, `Dotclear` and renders the result either in HTML, text or into -- another Wiki format. The Wiki engine is used in two steps: -- -- * The Wiki text is parsed according to its syntax to produce a Wiki Document instance. -- * The Wiki document is then rendered by a renderer to produce the final HTML, text. -- -- Through this process, it is possible to insert filters and plugins to customize the -- parsing and the rendering. -- -- [images/ada-wiki.png] -- -- The Ada Wiki engine is organized in several packages: -- -- * The [Wiki Streams](#wiki-streams) packages define the interface, types and operations -- for the Wiki engine to read the Wiki or HTML content and for the Wiki renderer to generate -- the HTML or text outputs. -- * The [Wiki parser](#wiki-parsers) is responsible for parsing HTML or Wiki content -- according to a selected Wiki syntax. It builds the final Wiki document through filters -- and plugins. -- * The [Wiki Filters](#wiki-filters) provides a simple filter framework that allows to plug -- specific filters when a Wiki document is parsed and processed. Filters are used for the -- table of content generation, for the HTML filtering, to collect words or links -- and so on. -- * The [Wiki Plugins](#wiki-plugins) defines the plugin interface that is used -- by the Wiki engine to provide pluggable extensions in the Wiki. Plugins are used -- for the Wiki template support, to hide some Wiki text content when it is rendered -- or to interact with other systems. -- * The Wiki documents and attributes are used for the representation of the Wiki -- document after the Wiki content is parsed. -- * The [Wiki renderers](@wiki-render) are the last packages which are used for the rendering -- of the Wiki document to produce the final HTML or text. -- -- @include-doc docs/Tutorial.md -- @include wiki-documents.ads -- @include wiki-attributes.ads -- @include wiki-parsers.ads -- @include wiki-filters.ads -- @include wiki-plugins.ads -- @include wiki-render.ads -- @include wiki-streams.ads package Wiki is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- Textile syntax -- https://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile SYNTAX_TEXTILE, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); -- Defines the possible text formats. type Format_Type is (BOLD, STRONG, ITALIC, EMPHASIS, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT); type Format_Map is array (Format_Type) of Boolean; -- The possible HTML tags as described in HTML5 specification. type Html_Tag is ( -- Section 4.1 The root element ROOT_HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Deprecated tags but still used widely TT_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag) return String_Access; type Tag_Boolean_Array is array (Html_Tag) of Boolean; No_End_Tag : constant Tag_Boolean_Array := ( BASE_TAG => True, LINK_TAG => True, META_TAG => True, IMG_TAG => True, HR_TAG => True, BR_TAG => True, WBR_TAG => True, INPUT_TAG => True, KEYGEN_TAG => True, others => False); Tag_Omission : constant Tag_Boolean_Array := ( -- Section 4.4 Grouping content LI_TAG => True, DT_TAG => True, DD_TAG => True, -- Section 4.5 Text-level semantics RB_TAG => True, RT_TAG => True, RTC_TAG => True, RP_TAG => True, -- Section 4.9 Tabular data TH_TAG => True, TD_TAG => True, TR_TAG => True, TBODY_TAG => True, THEAD_TAG => True, TFOOT_TAG => True, OPTGROUP_TAG => True, OPTION_TAG => True, others => False); end Wiki;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016, 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. ----------------------------------------------------------------------- -- = Wiki = -- The Wiki engine parses a Wiki text in several Wiki syntax such as `MediaWiki`, -- `Creole`, `Markdown`, `Dotclear` and renders the result either in HTML, text or into -- another Wiki format. The Wiki engine is used in two steps: -- -- * The Wiki text is parsed according to its syntax to produce a Wiki Document instance. -- * The Wiki document is then rendered by a renderer to produce the final HTML, text. -- -- Through this process, it is possible to insert filters and plugins to customize the -- parsing and the rendering. -- -- [images/ada-wiki.png] -- -- The Ada Wiki engine is organized in several packages: -- -- * The [Wiki Streams](#wiki-streams) packages define the interface, types and operations -- for the Wiki engine to read the Wiki or HTML content and for the Wiki renderer to generate -- the HTML or text outputs. -- * The [Wiki parser](#wiki-parsers) is responsible for parsing HTML or Wiki content -- according to a selected Wiki syntax. It builds the final Wiki document through filters -- and plugins. -- * The [Wiki Filters](#wiki-filters) provides a simple filter framework that allows to plug -- specific filters when a Wiki document is parsed and processed. Filters are used for the -- table of content generation, for the HTML filtering, to collect words or links -- and so on. -- * The [Wiki Plugins](#wiki-plugins) defines the plugin interface that is used -- by the Wiki engine to provide pluggable extensions in the Wiki. Plugins are used -- for the Wiki template support, to hide some Wiki text content when it is rendered -- or to interact with other systems. -- * The Wiki documents and attributes are used for the representation of the Wiki -- document after the Wiki content is parsed. -- * The [Wiki renderers](@wiki-render) are the last packages which are used for the rendering -- of the Wiki document to produce the final HTML or text. -- -- @include-doc docs/Tutorial.md -- @include wiki-documents.ads -- @include wiki-attributes.ads -- @include wiki-parsers.ads -- @include wiki-filters.ads -- @include wiki-plugins.ads -- @include wiki-render.ads -- @include wiki-streams.ads package Wiki is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- Textile syntax -- https://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile SYNTAX_TEXTILE, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); -- Defines the possible text formats. type Format_Type is (BOLD, STRONG, ITALIC, EMPHASIS, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT, INS); type Format_Map is array (Format_Type) of Boolean; -- The possible HTML tags as described in HTML5 specification. type Html_Tag is ( -- Section 4.1 The root element ROOT_HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Deprecated tags but still used widely TT_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag) return String_Access; type Tag_Boolean_Array is array (Html_Tag) of Boolean; No_End_Tag : constant Tag_Boolean_Array := ( BASE_TAG => True, LINK_TAG => True, META_TAG => True, IMG_TAG => True, HR_TAG => True, BR_TAG => True, WBR_TAG => True, INPUT_TAG => True, KEYGEN_TAG => True, others => False); Tag_Omission : constant Tag_Boolean_Array := ( -- Section 4.4 Grouping content LI_TAG => True, DT_TAG => True, DD_TAG => True, -- Section 4.5 Text-level semantics RB_TAG => True, RT_TAG => True, RTC_TAG => True, RP_TAG => True, -- Section 4.9 Tabular data TH_TAG => True, TD_TAG => True, TR_TAG => True, TBODY_TAG => True, THEAD_TAG => True, TFOOT_TAG => True, OPTGROUP_TAG => True, OPTION_TAG => True, others => False); -- Tags before and after which we want to preserve spaces. Tag_Text : constant Tag_Boolean_Array := ( A_TAG => True, EM_TAG => True, STRONG_TAG => True, SMALL_TAG => True, S_TAG => True, CITE_TAG => True, Q_TAG => True, DFN_TAG => True, ABBR_TAG => True, TIME_TAG => True, CODE_TAG => True, VAR_TAG => True, SAMP_TAG => True, KBD_TAG => True, SUB_TAG => True, SUP_TAG => True, I_TAG => True, B_TAG => True, MARK_TAG => True, RUBY_TAG => True, RT_TAG => True, RP_TAG => True, BDI_TAG => True, BDO_TAG => True, SPAN_TAG => True, INS_TAG => True, DEL_TAG => True, TT_TAG => True, UNKNOWN_TAG => True, others => False ); end Wiki;
Add Tag_Text to control whether we should not strip spaces before/after the given tag
Add Tag_Text to control whether we should not strip spaces before/after the given tag
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c08020b5c16a0dfb2421774f9f03e9b8c5b4cd47
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; Current_Level : Natural := 0; Quote_Level : Natural := 0; UL_List_Level : Natural := 0; OL_List_Level : Natural := 0; Current_Style : Format_Map := (others => False); Content : Unbounded_Wide_Wide_String; Link_Href : Unbounded_Wide_Wide_String; Link_Title : Unbounded_Wide_Wide_String; Link_Lang : Unbounded_Wide_Wide_String; end record; end Wiki.Render.Wiki;
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; with Wiki.Strings; -- == Wiki Renderer == -- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Wiki is use Standard.Wiki.Attributes; -- ------------------------------ -- Wiki to HTML writer -- ------------------------------ type Wiki_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Wiki_Renderer; Stream : in Streams.Output_Stream_Access; Format : in Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Add a section header in the document. procedure Render_Header (Engine : in out Wiki_Renderer; Header : in Wide_Wide_String; Level : in Positive); -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. procedure Add_Paragraph (Engine : in out Wiki_Renderer); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Wiki_Renderer; Level : in Natural); -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Add_List_Item (Engine : in out Wiki_Renderer; Level : in Positive; Ordered : in Boolean); -- Render a link. procedure Render_Link (Engine : in out Wiki_Renderer; Name : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Link : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Add a text block with the given format. procedure Render_Text (Engine : in out Wiki_Renderer; Text : in Wide_Wide_String; Format : in Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; type Wide_String_Access is access constant Wide_Wide_String; type Wiki_Tag_Type is (Header_Start, Header_End, Img_Start, Img_End, Link_Start, Link_End, Link_Separator, Quote_Start, Quote_End, Quote_Separator, Preformat_Start, Preformat_End, List_Start, List_Item, List_Ordered_Item, Line_Break, Escape_Rule, Horizontal_Rule, Blockquote_Start, Blockquote_End); type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access; type Wiki_Format_Array is array (Format_Type) of Wide_String_Access; -- Emit a new line. procedure New_Line (Engine : in out Wiki_Renderer); procedure Close_Paragraph (Engine : in out Wiki_Renderer); procedure Open_Paragraph (Engine : in out Wiki_Renderer); procedure Start_Keep_Content (Engine : in out Wiki_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; EMPTY_TAG : aliased constant Wide_Wide_String := ""; type Wiki_Renderer is new Renderer with record Output : Streams.Output_Stream_Access := null; Syntax : Wiki_Syntax := SYNTAX_CREOLE; Format : Format_Map := (others => False); Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access); Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access); Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set; Has_Paragraph : Boolean := False; Has_Item : Boolean := False; Need_Paragraph : Boolean := False; Empty_Line : Boolean := True; Keep_Content : Boolean := False; In_List : Boolean := False; Invert_Header_Level : Boolean := False; Allow_Link_Language : Boolean := False; Link_First : Boolean := False; Html_Blockquote : Boolean := False; 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;
Add Line_Count for the generator
Add Line_Count for the generator
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e8771ce084f4a09b508a4ff5420ab02727e5c53d
regtests/gen-integration-tests.ads
regtests/gen-integration-tests.ads
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with serialization code. procedure Test_Generate_Zargo_Serialization (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist with exclude support command. procedure Test_Dist_Exclude (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with serialization code. procedure Test_Generate_Zargo_Serialization (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
Declare the Test_Dist_Exclude procedure
Declare the Test_Dist_Exclude procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
5a79dcfb1bdafa849cd5abf1f6afddad1844b4c4
regtests/gen-integration-tests.ads
regtests/gen-integration-tests.ads
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Change the working directory before running dynamo. overriding procedure Set_Up (T : in out Test); -- Restore the working directory after running dynamo. overriding procedure Tear_Down (T : in out Test); -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with serialization code. procedure Test_Generate_Zargo_Serialization (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
Declare the Test_Generate_Zargo_Serialization procedure
Declare the Test_Generate_Zargo_Serialization procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
4aa53491672a65bc4864387009f0b2f638acceb7
awa/regtests/awa-mail-modules-tests.adb
awa/regtests/awa-mail-modules-tests.adb
----------------------------------------------------------------------- -- awa-mail-module-tests -- Unit tests for Mail 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 Util.Test_Caller; with AWA.Events; package body AWA.Mail.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Mail.Clients"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message", Test_Create_Message'Access); end Add_Tests; -- Create an email message and verify its content. procedure Test_Create_Message (T : in out Test) is use Util.Beans.Objects; Mail : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module; Event : AWA.Events.Module_Event; Props : Util.Beans.Objects.Maps.Map; begin T.Assert (Mail /= null, "There is no current mail module"); Props.Insert ("name", To_Object (String '("joe"))); Props.Insert ("email", To_Object (String '("[email protected]"))); Mail.Send_Mail (Template => "mail-info.html", Props => Props, Content => Event); end Test_Create_Message; end AWA.Mail.Modules.Tests;
----------------------------------------------------------------------- -- awa-mail-module-tests -- Unit tests for Mail module -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with AWA.Events; package body AWA.Mail.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Mail.Clients"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message", Test_Create_Message'Access); Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (CC:)", Test_Cc_Message'Access); Caller.Add_Test (Suite, "Test AWA.Mail.Module.Create_Message (BCC:)", Test_Bcc_Message'Access); end Add_Tests; -- ------------------------------ -- Create an email message with the given template and verify its content. -- ------------------------------ procedure Test_Mail_Message (T : in out Test; Name : in String) is use Util.Beans.Objects; Mail : constant AWA.Mail.Modules.Mail_Module_Access := AWA.Mail.Modules.Get_Mail_Module; Event : AWA.Events.Module_Event; Props : Util.Beans.Objects.Maps.Map; begin T.Assert (Mail /= null, "There is no current mail module"); Props.Insert ("name", To_Object (String '("joe"))); Props.Insert ("email", To_Object (String '("[email protected]"))); Mail.Send_Mail (Template => Name, Props => Props, Content => Event); end Test_Mail_Message; -- ------------------------------ -- Create an email message and verify its content. -- ------------------------------ procedure Test_Create_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-info.html"); end Test_Create_Message; -- ------------------------------ -- Create an email message with Cc: and verify its content. -- ------------------------------ procedure Test_Cc_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-cc.html"); end Test_Cc_Message; -- ------------------------------ -- Create an email message with Bcc: and verify its content. -- ------------------------------ procedure Test_Bcc_Message (T : in out Test) is begin T.Test_Mail_Message ("mail-bcc.html"); end Test_Bcc_Message; end AWA.Mail.Modules.Tests;
Add new tests for mail Cc and Bcc
Add new tests for mail Cc and Bcc
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
80a6291defaaa03388d197e25ead96a575b24eda
awa/plugins/awa-tags/src/awa-tags-components.ads
awa/plugins/awa-tags/src/awa-tags-components.ads
----------------------------------------------------------------------- -- awa-tags-components -- Tags component -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Beans.Objects; with Util.Strings.Vectors; with EL.Expressions; with ASF.Components.Html.Forms; with ASF.Contexts.Faces; with ASF.Contexts.Writer; with ASF.Events.Faces; with ASF.Factory; package AWA.Tags.Components is use ASF.Contexts.Writer; -- Get the Tags component factory. function Definition return ASF.Factory.Factory_Bindings_Access; -- ------------------------------ -- Input component -- ------------------------------ -- The AWA input component overrides the ASF input component to build a compact component -- that displays a label, the input field and the associated error message if necessary. -- -- The generated HTML looks like: -- -- <ul class='taglist'> -- <li><span>tag</span></li> -- </ul> -- -- or -- -- <input type='text' name='' value='tag'/> -- type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record -- List of tags that have been added. Added : Util.Strings.Vectors.Vector; -- List of tags that have been removed. Deleted : Util.Strings.Vectors.Vector; -- True if the submitted values are correct. Is_Valid : Boolean := False; end record; type Tag_UIInput_Access is access all Tag_UIInput'Class; -- Returns True if the tag component must be rendered as readonly. function Is_Readonly (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Get the tag after convertion with the optional converter. function Get_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the tag as a readonly item. procedure Render_Readonly_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag as a link. procedure Render_Link_Tag (UI : in Tag_UIInput; Name : in String; Tag : in Util.Beans.Objects.Object; Link : in EL.Expressions.Expression; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag for an input form. procedure Render_Form_Tag (UI : in Tag_UIInput; Id : in String; Tag : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>. procedure Render_Readonly (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the list of tags for a form. procedure Render_Form (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the javascript to enable the tag edition. procedure Render_Script (UI : in Tag_UIInput; Id : in String; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Get the action method expression to invoke if the command is pressed. -- ------------------------------ function Get_Action_Expression (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return EL.Expressions.Method_Expression; -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out Tag_UIInput; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end AWA.Tags.Components;
----------------------------------------------------------------------- -- awa-tags-components -- Tags component -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Beans.Objects; with Util.Strings.Vectors; with EL.Expressions; with ASF.Components.Html.Forms; with ASF.Contexts.Faces; with ASF.Contexts.Writer; with ASF.Events.Faces; with ASF.Factory; -- == Tags Component == -- -- === Displaying a list of tags === -- The <tt>awa:tagList</tt> component displays a list of tags. Each tag can be rendered as -- a link if the <tt>tagLink</tt> attribute is defined. The list of tags is passed in the -- <tt>value</tt> attribute. When rending that list, the <tt>var</tt> attribute is used to -- setup a variable with the tag value. The <tt>tagLink</tt> attribute is then evaluated -- against that variable and the result defines the link. -- -- <awa:tagList value='#{questionList.tags}' id='qtags' styleClass="tagedit-list" -- tagLink="#{contextPath}/questions/tagged.html?tag=#{tagName}" -- var="tagName" -- tagClass="tagedit-listelement tagedit-listelement-old"/> -- -- === Tag editing === -- The <tt>awa:tagList</tt> component allows to add or remove tags associated with a given -- database entity. The tag management works with the jQuery plugin <b>Tagedit</b>. For this, -- the page must include the <b>/js/jquery.tagedit.js</b> Javascript resource. -- -- The tag edition is active only if the <tt>awa:tagList</tt> component is placed within an -- <tt>h:form</tt> component. The <tt>value</tt> attribute defines the list of tags. This must -- be a <tt>Tag_List_Bean</tt> object. -- -- <awa:tagList value='#{question.tags}' id='qtags' -- autoCompleteUrl='#{contextPath}/questions/lists/tag-search.html'/> -- -- When the form is submitted and validated, the procedure <tt>Set_Added</tt> and -- <tt>Set_Deleted</tt> are called on the value bean with the list of tags that were -- added and removed. These operations are called in the <tt>UPDATE_MODEL_VALUES</tt> -- phase (ie, before calling the action's bean operation). -- package AWA.Tags.Components is use ASF.Contexts.Writer; -- Get the Tags component factory. function Definition return ASF.Factory.Factory_Bindings_Access; -- ------------------------------ -- Input component -- ------------------------------ -- The AWA input component overrides the ASF input component to build a compact component -- that displays a label, the input field and the associated error message if necessary. -- -- The generated HTML looks like: -- -- <ul class='taglist'> -- <li><span>tag</span></li> -- </ul> -- -- or -- -- <input type='text' name='' value='tag'/> -- type Tag_UIInput is new ASF.Components.Html.Forms.UIInput with record -- List of tags that have been added. Added : Util.Strings.Vectors.Vector; -- List of tags that have been removed. Deleted : Util.Strings.Vectors.Vector; -- True if the submitted values are correct. Is_Valid : Boolean := False; end record; type Tag_UIInput_Access is access all Tag_UIInput'Class; -- Returns True if the tag component must be rendered as readonly. function Is_Readonly (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Get the tag after convertion with the optional converter. function Get_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the tag as a readonly item. procedure Render_Readonly_Tag (UI : in Tag_UIInput; Tag : in Util.Beans.Objects.Object; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag as a link. procedure Render_Link_Tag (UI : in Tag_UIInput; Name : in String; Tag : in Util.Beans.Objects.Object; Link : in EL.Expressions.Expression; Class : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the tag for an input form. procedure Render_Form_Tag (UI : in Tag_UIInput; Id : in String; Tag : in Util.Beans.Objects.Object; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- a link is rendered for each tag. Otherwise, each tag is rendered as a <tt>span</tt>. procedure Render_Readonly (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the list of tags for a form. procedure Render_Form (UI : in Tag_UIInput; List : in Util.Beans.Basic.List_Bean_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the javascript to enable the tag edition. procedure Render_Script (UI : in Tag_UIInput; Id : in String; Writer : in Response_Writer_Access; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the input component. Starts the DL/DD list and write the input -- component with the possible associated error message. overriding procedure Encode_Begin (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Render the end of the input component. Closes the DL/DD list. overriding procedure Encode_End (UI : in Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Get the action method expression to invoke if the command is pressed. function Get_Action_Expression (UI : in Tag_UIInput; Context : in ASF.Contexts.Faces.Faces_Context'Class) return EL.Expressions.Method_Expression; -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out Tag_UIInput; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Broadcast the event to the event listeners installed on this component. -- Listeners are called in the order in which they were added. overriding procedure Broadcast (UI : in out Tag_UIInput; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end AWA.Tags.Components;
Document how to use the <awa:tagList> component
Document how to use the <awa:tagList> component
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
ad07d073f030e1f6a32c60fb8e2cc06729678b1c
awa/plugins/awa-wikis/src/awa-wikis-previews.adb
awa/plugins/awa-wikis/src/awa-wikis-previews.adb
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- Copyright (C) 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Files; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO; with EL.Contexts.TLS; with Servlet.Core; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Services.Contexts; with AWA.Modules.Get; package body AWA.Wikis.Previews is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Preview"); -- ------------------------------ -- The worker procedure that performs the preview job. -- ------------------------------ procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Previewer : constant Preview_Module_Access := Get_Preview_Module; begin Previewer.Do_Preview_Job (Job); end Preview_Worker; -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wiki preview module"); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Preview_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Template := Plugin.Get_Config (PARAM_PREVIEW_TEMPLATE); Plugin.Command := Plugin.Get_Config (PARAM_PREVIEW_COMMAND); Plugin.Html := Plugin.Get_Config (PARAM_PREVIEW_HTML); Plugin.Add_Listener (AWA.Wikis.Modules.NAME, Plugin'Unchecked_Access); Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; Plugin.Job_Module.Register (Definition => Preview_Job_Definition.Factory); end Configure; -- ------------------------------ -- Execute the preview job and make the thumbnail preview. The page is first rendered in -- an HTML text file and the preview is rendered by using an external command. -- ------------------------------ procedure Do_Preview_Job (Plugin : in Preview_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is pragma Unreferenced (Job); use Util.Beans.Objects; Ctx : constant EL.Contexts.ELContext_Access := EL.Contexts.TLS.Current; Template : constant String := To_String (Plugin.Template.Get_Value (Ctx.all)); Command : constant String := To_String (Plugin.Command.Get_Value (Ctx.all)); Html_File : constant String := To_String (Plugin.Html.Get_Value (Ctx.all)); begin Log.Info ("Preview {0} with {1}", Template, Command); declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Dispatcher : constant Servlet.Core.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); Result : Ada.Strings.Unbounded.Unbounded_String; begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); Servlet.Core.Forward (Dispatcher, Req, Reply); Reply.Read_Content (Result); Util.Files.Write_File (Html_File, Result); end; declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Log.Info ("Running preview command {0}", Command); Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Line, False); Log.Info ("Received: {0}", Line); end; end loop; Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Do_Preview_Job; -- ------------------------------ -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. -- ------------------------------ procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("wiki_space_id", Page.Get_Wiki); J.Set_Parameter ("wiki_page_id", Page); J.Schedule (Preview_Job_Definition.Factory.all); end Make_Preview_Job; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. -- ------------------------------ overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. -- ------------------------------ overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. -- ------------------------------ overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Delete; -- ------------------------------ -- Get the preview module instance associated with the current application. -- ------------------------------ function Get_Preview_Module return Preview_Module_Access is function Get is new AWA.Modules.Get (Preview_Module, Preview_Module_Access, NAME); begin return Get; end Get_Preview_Module; end AWA.Wikis.Previews;
----------------------------------------------------------------------- -- awa-wikis-previews -- Wiki preview management -- Copyright (C) 2015, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Files; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Texts; with EL.Contexts.TLS; with Servlet.Core; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Services.Contexts; with AWA.Modules.Get; package body AWA.Wikis.Previews is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Wikis.Preview"); -- ------------------------------ -- The worker procedure that performs the preview job. -- ------------------------------ procedure Preview_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Previewer : constant Preview_Module_Access := Get_Preview_Module; begin Previewer.Do_Preview_Job (Job); end Preview_Worker; -- ------------------------------ -- Initialize the wikis module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Preview_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the wiki preview module"); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Preview_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Template := Plugin.Get_Config (PARAM_PREVIEW_TEMPLATE); Plugin.Command := Plugin.Get_Config (PARAM_PREVIEW_COMMAND); Plugin.Html := Plugin.Get_Config (PARAM_PREVIEW_HTML); Plugin.Add_Listener (AWA.Wikis.Modules.NAME, Plugin'Unchecked_Access); Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; Plugin.Job_Module.Register (Definition => Preview_Job_Definition.Factory); end Configure; -- ------------------------------ -- Execute the preview job and make the thumbnail preview. The page is first rendered in -- an HTML text file and the preview is rendered by using an external command. -- ------------------------------ procedure Do_Preview_Job (Plugin : in Preview_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is pragma Unreferenced (Job); use Util.Beans.Objects; Ctx : constant EL.Contexts.ELContext_Access := EL.Contexts.TLS.Current; Template : constant String := To_String (Plugin.Template.Get_Value (Ctx.all)); Command : constant String := To_String (Plugin.Command.Get_Value (Ctx.all)); Html_File : constant String := To_String (Plugin.Html.Get_Value (Ctx.all)); begin Log.Info ("Preview {0} with {1}", Template, Command); declare Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Dispatcher : constant Servlet.Core.Request_Dispatcher := Plugin.Get_Application.Get_Request_Dispatcher (Template); Result : Ada.Strings.Unbounded.Unbounded_String; begin Req.Set_Request_URI (Template); Req.Set_Method ("GET"); Servlet.Core.Forward (Dispatcher, Req, Reply); Reply.Read_Content (Result); Util.Files.Write_File (Html_File, Result); end; declare Pipe : aliased Util.Streams.Pipes.Pipe_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Log.Info ("Running preview command {0}", Command); Pipe.Open (Command, Util.Processes.READ_ALL); Input.Initialize (Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Line, False); Log.Info ("Received: {0}", Line); end; end loop; Pipe.Close; if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Do_Preview_Job; -- ------------------------------ -- Create a preview job and schedule the job to generate a new thumbnail preview for the page. -- ------------------------------ procedure Make_Preview_Job (Plugin : in Preview_Module; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("wiki_space_id", Page.Get_Wiki); J.Set_Parameter ("wiki_page_id", Page); J.Schedule (Preview_Job_Definition.Factory.all); end Make_Preview_Job; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the page. -- ------------------------------ overriding procedure On_Create (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the page. -- ------------------------------ overriding procedure On_Update (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin Instance.Make_Preview_Job (Item); end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the page. -- ------------------------------ overriding procedure On_Delete (Instance : in Preview_Module; Item : in AWA.Wikis.Models.Wiki_Page_Ref'Class) is begin null; end On_Delete; -- ------------------------------ -- Get the preview module instance associated with the current application. -- ------------------------------ function Get_Preview_Module return Preview_Module_Access is function Get is new AWA.Modules.Get (Preview_Module, Preview_Module_Access, NAME); begin return Get; end Get_Preview_Module; end AWA.Wikis.Previews;
Remove unused with clause
Remove unused with clause
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2e362e5a8261b6521e980cd1f153f75a0f3a0c95
src/decls-d_taula_de_noms.ads
src/decls-d_taula_de_noms.ads
-- ------------------------------------------------ -- Paquet de declaracions de la taula de noms -- ------------------------------------------------ -- Versió : 0.1 -- Autors : José Ruiz Bravo -- Biel Moyà Alcover -- Álvaro Medina Ballester -- ------------------------------------------------ -- Aquí una petita descripció. -- -- ------------------------------------------------ with decls.dgenerals; use decls.dgenerals; with Ada.Text_IO; use Ada.Text_IO; package decls.d_taula_de_noms is --pragma(pure); type taula_de_noms is private; procedure tbuida(tn : out taula_de_noms); procedure posa(tn : in out taula_de_noms; idn : out id_nom ; nom : in string); procedure imprimir_tcar(tn : in taula_de_noms; nparaules : integer); --function cons(tn : in taula_de_noms; idn : in id_nom ) return string; --procedure posa(tn : in out taula_de_noms; s : in string; ids : out string); --function cons(tn : in taula_de_noms; ids : in string) return string; private longitut :constant integer := 40; num_dispersio : constant integer := 255; type rang_dispersio is new integer range -1..num_dispersio; type rang_tcaracters is new integer range 0..(longitut*max_id)-1 ;--longitut d'una paraula * nombre paraules dispersio_nul : rang_dispersio := -1; type t_identificador is record pos_tcaracters: rang_tcaracters; seguent : id_nom; long_paraula : Natural;--aixo es logic, a mes es un apao, ja que al recorrer, el string es molt mes senzill! end record; type taula_dispersio is array (rang_dispersio) of id_nom; type taula_identificadors is array (id_nom) of t_identificador ; type taula_caracters is array (rang_tcaracters) of character ; type taula_de_noms is record td : taula_dispersio; tid : taula_identificadors; tc : taula_caracters; nid : id_nom; ncar : rang_tcaracters; end record; function fdisp (nom: in string) return rang_dispersio; end decls.d_taula_de_noms;
-- ------------------------------------------------ -- Paquet de declaracions de la taula de noms -- ------------------------------------------------ -- Versió : 0.1 -- Autors : José Ruiz Bravo -- Biel Moyà Alcover -- Álvaro Medina Ballester -- ------------------------------------------------ -- Aquí una petita descripció. -- -- ------------------------------------------------ with decls.dgenerals; use decls.dgenerals; with Ada.Text_IO; use Ada.Text_IO; package decls.d_taula_de_noms is --pragma(pure); type taula_de_noms is private; procedure tbuida(tn : out taula_de_noms); procedure posa(tn : in out taula_de_noms; idn : out id_nom ; nom : in string); procedure imprimir_tcar(tn : in taula_de_noms; nparaules : integer); --function cons(tn : in taula_de_noms; idn : in id_nom ) return string; --procedure posa(tn : in out taula_de_noms; s : in string; ids : out string); --function cons(tn : in taula_de_noms; ids : in string) return string; private longitut :constant integer := 40; num_dispersio : constant integer := 255; type rang_dispersio is new integer range -1..num_dispersio; type rang_tcaracters is new integer range 0..(longitut*max_id)-1 ;--longitut d'una paraula * nombre paraules dispersio_nul : rang_dispersio := -1; type t_identificador is record pos_tcaracters: rang_tcaracters; seguent : id_nom; long_paraula : Natural;--aixo es logic, a mes es un apao, ja que al recorrer, el string es molt mes senzill! end record; type taula_dispersio is array (rang_dispersio) of id_nom; type taula_identificadors is array (id_nom) of t_identificador ; type taula_caracters is array (rang_tcaracters) of character ; type taula_de_noms is record td : taula_dispersio; tid : taula_identificadors; tc : taula_caracters; nid : id_nom; ncar : rang_tcaracters; end record; function fdisp (nom: in string) return rang_dispersio; end decls.d_taula_de_noms;
Prueba con 2 palabras
Prueba con 2 palabras git-svn-id: 21e5e84ea84925cd81557fe364e06047ebebbce6@6 92701e50-6359-0410-9b06-881c3d199c04
Ada
mit
alvaromb/Compilemon
a6c6d3aaf307ccfffb25adcaed2807d8dea14d13
awa/plugins/awa-images/regtests/awa-images-services-tests.adb
awa/plugins/awa-images/regtests/awa-images-services-tests.adb
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Storages.Beans.Factories; with AWA.Tests.Helpers.Users; with AWA.Images.Modules; package body AWA.Images.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Images.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Images.Create_Image", Test_Create_Image'Access); end Add_Tests; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg"); Thumb : constant String := Util.Tests.Get_Test_Path ("bast-12-thumb.jpg"); Width : Natural; Height : Natural; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Images.Modules.Get_Image_Manager; T.Manager.Create_Thumbnail (Source, Thumb, Width, Height); end Test_Create_Image; end AWA.Images.Services.Tests;
----------------------------------------------------------------------- -- awa-storages-services-tests -- Unit tests for storage service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Services.Contexts; with AWA.Storages.Modules; with AWA.Storages.Beans.Factories; with AWA.Tests.Helpers.Users; with AWA.Images.Modules; package body AWA.Images.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Images.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Images.Create_Image", Test_Create_Image'Access); end Add_Tests; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg"); Thumb : constant String := Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg"); Width : Natural; Height : Natural; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Images.Modules.Get_Image_Manager; T.Manager.Create_Thumbnail (Source, Thumb, Width, Height); Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width"); Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height"); end Test_Create_Image; end AWA.Images.Services.Tests;
Check the image width and height for the unit test.
Check the image width and height for the unit test.
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
73ba56b0904902cebf9509f563adb9726f13bf8f
src/security-controllers-roles.adb
src/security-controllers-roles.adb
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Security.Controllers.Roles is -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. -- ------------------------------ function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then for I in Handler.Roles'Range loop -- if P.Has_Role (Handler.Roles (I)) then return True; -- end if; end loop; end if; return False; end Has_Permission; end Security.Controllers.Roles;
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Security.Controllers.Roles is -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. -- ------------------------------ function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is pragma Unreferenced (Permission); use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; Roles : Security.Policies.Roles.Role_Map; begin if P /= null then -- If the principal has some roles, get them. if P.all in Policies.Roles.Role_Principal_Context'Class then Roles := Policies.Roles.Role_Principal_Context'Class (P.all).Get_Roles; else return False; end if; for I in Handler.Roles'Range loop if Roles (Handler.Roles (I)) then return True; end if; end loop; end if; return False; end Has_Permission; end Security.Controllers.Roles;
Check if the principal implements the Role_Principal_Context interface and get the user's roles with it
Check if the principal implements the Role_Principal_Context interface and get the user's roles with it
Ada
apache-2.0
Letractively/ada-security
07bcee95021f36bdcfab38b9e1a1ce5f34172a1b
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The process is the following: -- -- o <b>Initialize</b> is called to configure the OpenID realm and set the -- OpenID return callback CB. -- o <b>Discover</b> is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- o <b>Associate</b> is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- o <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- o The user should be redirected to the authentication URL. -- o The OpenID provider authenticate the user and redirects the user to the callback CB. -- o The association is decoded from the callback parameter. -- o <b>Verify</b> is called with the association to check the result and -- obtain the authentication results. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- === Authentication process == -- The process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
Document the OpenID process
Document the OpenID process
Ada
apache-2.0
stcarrez/ada-security
f16023ad92a6be1cf7665cdc9c6cc44e4b920d21
src/gen-commands.ads
src/gen-commands.ads
----------------------------------------------------------------------- -- gen-commands -- Commands for dynamo -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Gen.Generator; package Gen.Commands is package Drivers is new Util.Commands.Drivers (Context_Type => Gen.Generator.Handler, Driver_Name => "gen-commands"); subtype Command is Drivers.Command_Type; subtype Command_Access is Drivers.Command_Access; subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; -- Print dynamo short usage. procedure Short_Help_Usage; end Gen.Commands;
----------------------------------------------------------------------- -- gen-commands -- Commands for dynamo -- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Commands.Parsers; with Gen.Generator; package Gen.Commands is package Drivers is new Util.Commands.Drivers (Context_Type => Gen.Generator.Handler, Config_Parser => Util.Commands.Parsers.No_Parser, Driver_Name => "gen-commands"); subtype Command is Drivers.Command_Type; subtype Command_Access is Drivers.Command_Access; subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; -- Print dynamo short usage. procedure Short_Help_Usage; end Gen.Commands;
Update to use the No_Parser for commands
Update to use the No_Parser for commands
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
b8487f39af963fa2971188795fe1b145f4a7aa15
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
awa/plugins/awa-blogs/src/awa-blogs-beans.adb
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with AWA.Helpers.Requests; with AWA.Helpers.Selectors; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_Uri, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); elsif Name = POST_USERNAME_ATTR then return Util.Beans.Objects.To_Object (String '(From.Post.Get_Author.Get_Name)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_STATUS_ATTR then From.Post.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_Uri; -- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of -- objects does not work yet. Force loading the user here while the above -- session is still open. declare A : constant String := String '(Object.Post.Get_Author.Get_Name); pragma Unreferenced (A); begin null; end; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; function Create_From_Status is new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, "blog_status_"); -- ------------------------------ -- Get a select item list which contains a list of post status. -- ------------------------------ function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Helpers; begin return Selectors.Create_Selector_Bean (Bundle => "blogs", Context => null, Create => Create_From_Status'Access).all'Access; end Create_Status_List; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Services.Contexts; with AWA.Blogs.Services; with AWA.Helpers.Requests; with AWA.Helpers.Selectors; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_Uri, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text, Status => Bean.Post.Get_Status); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); elsif Name = POST_USERNAME_ATTR then return Util.Beans.Objects.To_Object (String '(From.Post.Get_Author.Get_Name)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_Uri (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_STATUS_ATTR then From.Post.Set_Status (AWA.Blogs.Models.Post_Status_Type_Objects.To_Value (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_Uri; -- SCz: 2012-05-19: workaround for ADO 0.3 limitation. The lazy loading of -- objects does not work yet. Force loading the user here while the above -- session is still open. declare A : constant String := String '(Object.Post.Get_Author.Get_Name); pragma Unreferenced (A); begin null; end; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := AWA.Helpers.Requests.Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; function Create_From_Status is new AWA.Helpers.Selectors.Create_From_Enum (AWA.Blogs.Models.Post_Status_Type, "blog_status_"); -- ------------------------------ -- Get a select item list which contains a list of post status. -- ------------------------------ function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Helpers; begin return Selectors.Create_Selector_Bean (Bundle => "blogs", Context => null, Create => Create_From_Status'Access).all'Access; end Create_Status_List; end AWA.Blogs.Beans;
Simplify the implementation
Simplify the implementation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c14600b6f92588bef059e9ea7333a18a13986ec9
src/wiki-render-links.ads
src/wiki-render-links.ads
----------------------------------------------------------------------- -- wiki-render-links -- Wiki links renderering -- 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. ----------------------------------------------------------------------- -- === Link Renderer === -- The <tt>Wiki.Render.Links</tt> package defines the <tt>Link_Renderer</tt> interface used -- for the rendering of links and images. The interface allows to customize the generated -- links and image source for the final HTML. -- package Wiki.Render.Links is pragma Preelaborate; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean); end Wiki.Render.Links;
----------------------------------------------------------------------- -- wiki-render-links -- Wiki links renderering -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; -- === Link Renderer === -- The <tt>Wiki.Render.Links</tt> package defines the <tt>Link_Renderer</tt> interface used -- for the rendering of links and images. The interface allows to customize the generated -- links and image source for the final HTML. -- package Wiki.Render.Links is pragma Preelaborate; type Link_Renderer is limited interface; type Link_Renderer_Access is access all Link_Renderer'Class; -- Get the image link that must be rendered from the wiki image link. procedure Make_Image_Link (Renderer : in Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : out Natural; Height : out Natural) is abstract; -- Get the page link that must be rendered from the wiki page link. procedure Make_Page_Link (Renderer : in Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean) is abstract; type Default_Link_Renderer is new Link_Renderer with null record; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Default_Link_Renderer; Link : in Wiki.Strings.WString; URI : out Wiki.Strings.UString; Exists : out Boolean); end Wiki.Render.Links;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9ee3496b8b0d8b9094e876a73b8c3127ef4c6c49
src/wiki-plugins.ads
src/wiki-plugins.ads
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Previous : access Plugin_Context; Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; Syntax : Wiki.Wiki_Syntax; Is_Hidden : Boolean := False; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; end Wiki.Plugins;
----------------------------------------------------------------------- -- wiki-plugins -- Wiki plugins -- Copyright (C) 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Documents; with Wiki.Filters; -- == Plugins == -- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki -- engine to provide pluggable extensions in the Wiki. -- package Wiki.Plugins is pragma Preelaborate; type Plugin_Context; type Wiki_Plugin is limited interface; type Wiki_Plugin_Access is access all Wiki_Plugin'Class; type Plugin_Factory is limited interface; type Plugin_Factory_Access is access all Plugin_Factory'Class; -- Find a plugin knowing its name. function Find (Factory : in Plugin_Factory; Name : in String) return Wiki_Plugin_Access is abstract; type Plugin_Context is limited record Previous : access Plugin_Context; Filters : Wiki.Filters.Filter_Chain; Factory : Plugin_Factory_Access; Variables : Wiki.Attributes.Attribute_List; Syntax : Wiki.Wiki_Syntax; Is_Hidden : Boolean := False; Is_Included : Boolean := False; end record; -- Expand the plugin configured with the parameters for the document. procedure Expand (Plugin : in out Wiki_Plugin; Document : in out Wiki.Documents.Document; Params : in out Wiki.Attributes.Attribute_List; Context : in Plugin_Context) is abstract; end Wiki.Plugins;
Add Is_Included boolean flag in the context
Add Is_Included boolean flag in the context
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5ff5c3cecdee5b26ac310c92995676574d097752
src/util-beans-basic-lists.ads
src/util-beans-basic-lists.ads
----------------------------------------------------------------------- -- Util.Beans.Basic.Lists -- List bean given access to a vector -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Containers; with Ada.Containers.Vectors; with Util.Beans.Objects; -- The <b>Util.Beans.Basic.Lists</b> generic package implements a list of -- elements that can be accessed through the <b>List_Bean</b> interface. generic type Element_Type is new Util.Beans.Basic.Readonly_Bean with private; package Util.Beans.Basic.Lists is -- Package that represents the vectors of elements. -- (gcc 4.4 crashes if this package is defined as generic parameter. package Vectors is new Ada.Containers.Vectors (Element_Type => Element_Type, Index_Type => Natural); -- The list of elements is defined in a public part so that applications -- can easily add or remove elements in the target list. The <b>List_Bean</b> -- type holds the real implementation with the private parts. type Abstract_List_Bean is abstract new Ada.Finalization.Controlled and Util.Beans.Basic.List_Bean with record List : Vectors.Vector; end record; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> type gives access to a list of objects. type List_Bean is new Abstract_List_Bean with private; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Bean) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Bean; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Bean) 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 List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Initialize the list bean. overriding procedure Initialize (Object : in out List_Bean); -- Deletes the list bean procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access); private type List_Bean is new Abstract_List_Bean with record Current : aliased Element_Type; Row : Util.Beans.Objects.Object; end record; end Util.Beans.Basic.Lists;
----------------------------------------------------------------------- -- Util.Beans.Basic.Lists -- List bean given access to a vector -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Containers; with Ada.Containers.Vectors; with Util.Beans.Objects; -- The <b>Util.Beans.Basic.Lists</b> generic package implements a list of -- elements that can be accessed through the <b>List_Bean</b> interface. generic type Element_Type is new Util.Beans.Basic.Readonly_Bean with private; package Util.Beans.Basic.Lists is -- Package that represents the vectors of elements. -- (gcc 4.4 crashes if this package is defined as generic parameter. package Vectors is new Ada.Containers.Vectors (Element_Type => Element_Type, Index_Type => Natural); -- The list of elements is defined in a public part so that applications -- can easily add or remove elements in the target list. The <b>List_Bean</b> -- type holds the real implementation with the private parts. type Abstract_List_Bean is abstract new Ada.Finalization.Controlled and Util.Beans.Basic.List_Bean with record List : aliased Vectors.Vector; end record; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> type gives access to a list of objects. type List_Bean is new Abstract_List_Bean with private; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. overriding function Get_Count (From : in List_Bean) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out List_Bean; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in List_Bean) 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 List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Initialize the list bean. overriding procedure Initialize (Object : in out List_Bean); -- Deletes the list bean procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access); private type List_Bean is new Abstract_List_Bean with record Current : aliased Element_Type; Row : Util.Beans.Objects.Object; end record; end Util.Beans.Basic.Lists;
Make the List an aliased member to help the Rest operations
Make the List an aliased member to help the Rest operations
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
48df0eaacf291b08d320713e6f15857cfe227565
src/gen.ads
src/gen.ads
----------------------------------------------------------------------- -- Gen -- Code 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. ----------------------------------------------------------------------- package Gen is -- Library SVN identification SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk"; -- Revision used (must run 'make version' to update) SVN_REV : constant Positive := 339; end Gen;
----------------------------------------------------------------------- -- Gen -- Code 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. ----------------------------------------------------------------------- package Gen is -- Library SVN identification SVN_URL : constant String := "https://ada-gen.googlecode.com/svn/trunk"; -- Revision used (must run 'make version' to update) SVN_REV : constant Positive := 395; end Gen;
Update the version
Update the version
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
0aa46ce7066f92bcb22d8f35e74aa8bcd633d3c9
src/wiki-streams-builders.adb
src/wiki-streams-builders.adb
----------------------------------------------------------------------- -- wiki-writers-builders -- Wiki writer to a string builder -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with GNAT.Encode_UTF8_String; package body Wiki.Streams.Builders is use Wiki.Strings; package WBS renames Wiki.Strings.Wide_Wide_Builders; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wide_Wide_String) is begin WBS.Append (Stream.Content, Content); end Write; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wide_Wide_Character) is begin WBS.Append (Stream.Content, Content); end Write; -- Write the string to the string builder. procedure Write_String (Stream : in out Output_Builder_Stream; Content : in STring) is begin for I in Content'Range loop WBS.Append (Stream.Content, Ada.Characters.Conversions.To_Wide_Wide_Character (Content (I))); end loop; end Write_String; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Output_Builder_Stream; Process : not null access procedure (Chunk : in Wide_Wide_String)) is begin Wide_Wide_Builders.Iterate (Source.Content, Process); end Iterate; -- ------------------------------ -- Convert what was collected in the writer builder to a string and return it. -- ------------------------------ function To_String (Source : in Output_Builder_Stream) return String is procedure Convert (Chunk : in Wide_Wide_String); Pos : Natural := 1; Result : String (1 .. 5 * Wide_Wide_Builders.Length (Source.Content)); procedure Convert (Chunk : in Wide_Wide_String) is begin for I in Chunk'Range loop GNAT.Encode_UTF8_String.Encode_Wide_Wide_Character (Char => Chunk (I), Result => Result, Ptr => Pos); end loop; end Convert; begin Wide_Wide_Builders.Iterate (Source.Content, Convert'Access); return Result (1 .. Pos - 1); end To_String; end Wiki.Streams.Builders;
----------------------------------------------------------------------- -- wiki-writers-builders -- Wiki writer to a string builder -- 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 GNAT.Encode_UTF8_String; package body Wiki.Streams.Builders is use Wiki.Strings; package WBS renames Wiki.Strings.Wide_Wide_Builders; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wide_Wide_String) is begin WBS.Append (Stream.Content, Content); end Write; -- ------------------------------ -- Write the content to the string builder. -- ------------------------------ overriding procedure Write (Stream : in out Output_Builder_Stream; Content : in Wide_Wide_Character) is begin WBS.Append (Stream.Content, Content); end Write; -- Write the string to the string builder. procedure Write_String (Stream : in out Output_Builder_Stream; Content : in String) is begin for I in Content'Range loop WBS.Append (Stream.Content, Wiki.Strings.To_WChar (Content (I))); end loop; end Write_String; -- ------------------------------ -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. -- ------------------------------ procedure Iterate (Source : in Output_Builder_Stream; Process : not null access procedure (Chunk : in Wide_Wide_String)) is begin Wide_Wide_Builders.Iterate (Source.Content, Process); end Iterate; -- ------------------------------ -- Convert what was collected in the writer builder to a string and return it. -- ------------------------------ function To_String (Source : in Output_Builder_Stream) return String is procedure Convert (Chunk : in Wide_Wide_String); Pos : Natural := 1; Result : String (1 .. 5 * Wide_Wide_Builders.Length (Source.Content)); procedure Convert (Chunk : in Wide_Wide_String) is begin for I in Chunk'Range loop GNAT.Encode_UTF8_String.Encode_Wide_Wide_Character (Char => Chunk (I), Result => Result, Ptr => Pos); end loop; end Convert; begin Wide_Wide_Builders.Iterate (Source.Content, Convert'Access); return Result (1 .. Pos - 1); end To_String; end Wiki.Streams.Builders;
Use the To_WChar function
Use the To_WChar function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
b52dc3087cfb8733530bf774734f29614896f7c5
regtests/security-permissions-tests.adb
regtests/security-permissions-tests.adb
----------------------------------------------------------------------- -- Security-permissions-tests - Unit tests for Security.Permissions -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; package body Security.Permissions.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Permissions"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission", Test_Add_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index", Test_Add_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role", Test_Create_Role'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission", Test_Has_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy", Test_Read_Policy'Access); -- These tests are identical but registered under different names -- for the test documentation. Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission", Test_Role_Policy'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy", Test_Role_Policy'Access); end Add_Tests; -- ------------------------------ -- Returns true if the given permission is stored in the user principal. -- ------------------------------ function Has_Role (User : in Test_Principal; Role : in Role_Type) return Boolean is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Test_Principal) return String is begin return Util.Strings.To_String (From.Name); end Get_Name; -- ------------------------------ -- Test Add_Permission and Get_Permission_Index -- ------------------------------ procedure Test_Add_Permission (T : in out Test) is Index1, Index2 : Permission_Index; begin Add_Permission ("test-create-permission", Index1); T.Assert (Index1 = Get_Permission_Index ("test-create-permission"), "Get_Permission_Index failed"); Add_Permission ("test-create-permission", Index2); T.Assert (Index2 = Index1, "Add_Permission failed"); end Test_Add_Permission; -- ------------------------------ -- Test Create_Role and Get_Role_Name -- ------------------------------ procedure Test_Create_Role (T : in out Test) is M : Security.Permissions.Permission_Manager; Role : Role_Type; begin M.Create_Role (Name => "admin", Role => Role); Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name"); for I in Role + 1 .. Role_Type'Last loop declare Name : constant String := "admin-" & Role_Type'Image (I); Role2 : Role_Type; begin Role2 := M.Find_Role ("admin"); T.Assert (Role2 = Role, "Find_Role returned an invalid role"); M.Create_Role (Name => Name, Role => Role2); Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name"); end; end loop; end Test_Create_Role; -- ------------------------------ -- Test Has_Permission -- ------------------------------ procedure Test_Has_Permission (T : in out Test) is M : Security.Permissions.Permission_Manager; Perm : Permission_Type; User : Test_Principal; begin T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission"); end Test_Has_Permission; -- ------------------------------ -- Test reading policy files -- ------------------------------ procedure Test_Read_Policy (T : in out Test) is M : aliased Security.Permissions.Permission_Manager; Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Role_Type; Manager_Perm : Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, "empty.xml")); M.Add_Role_Type (Name => "admin", Result => Admin_Perm); M.Add_Role_Type (Name => "manager", Result => Manager_Perm); M.Read_Policy (Util.Files.Compose (Path, "simple-policy.xml")); User.Roles (Admin_Perm) := True; Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/" & Util.Strings.Image (I) & "/l.html"; P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache miss)"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare URI : constant String := "/admin/home/list.html"; P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission not granted"); end; end loop; Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)"); end; end Test_Read_Policy; -- ------------------------------ -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. -- ------------------------------ procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String) is M : aliased Security.Permissions.Permission_Manager; Dir : constant String := "regtests/files/permissions/"; Path : constant String := Util.Tests.Get_Path (Dir); User : aliased Test_Principal; Admin_Perm : Role_Type; Context : aliased Security.Contexts.Security_Context; begin M.Read_Policy (Util.Files.Compose (Path, File)); Admin_Perm := M.Find_Role (Role); Context.Set_Context (Manager => M'Unchecked_Access, Principal => User'Unchecked_Access); declare P : constant URI_Permission (URI'Length) := URI_Permission '(Len => URI'Length, URI => URI); begin -- A user without the role should not have the permission. T.Assert (not M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was granted for user without role. URI=" & URI); -- Set the role. User.Roles (Admin_Perm) := True; T.Assert (M.Has_Permission (Context => Context'Unchecked_Access, Permission => P), "Permission was not granted for user with role. URI=" & URI); end; end Check_Policy; -- ------------------------------ -- Test reading policy files and using the <role-permission> controller -- ------------------------------ procedure Test_Role_Policy (T : in out Test) is begin T.Check_Policy (File => "policy-with-role.xml", Role => "developer", URI => "/developer/user-should-have-developer-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/developer/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "manager", URI => "/manager/user-should-have-manager-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/manager/user-should-have-admin-role"); T.Check_Policy (File => "policy-with-role.xml", Role => "admin", URI => "/admin/user-should-have-admin-role"); end Test_Role_Policy; end Security.Permissions.Tests;
----------------------------------------------------------------------- -- Security-permissions-tests - Unit tests for Security.Permissions -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Files; with Util.Test_Caller; with Util.Measures; with Security.Contexts; package body Security.Permissions.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Security.Permissions"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission", Test_Add_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index", Test_Add_Permission'Access); end Add_Tests; -- ------------------------------ -- Test Add_Permission and Get_Permission_Index -- ------------------------------ procedure Test_Add_Permission (T : in out Test) is Index1, Index2 : Permission_Index; begin Add_Permission ("test-create-permission", Index1); T.Assert (Index1 = Get_Permission_Index ("test-create-permission"), "Get_Permission_Index failed"); Add_Permission ("test-create-permission", Index2); T.Assert (Index2 = Index1, "Add_Permission failed"); end Test_Add_Permission; end Security.Permissions.Tests;
Remove the policy specific unit test
Remove the policy specific unit test
Ada
apache-2.0
stcarrez/ada-security
f5e1937db46683da66fb5c5221e66a619887996e
src/util-beans-basic.ads
src/util-beans-basic.ads
----------------------------------------------------------------------- -- Util.Beans.Basic -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; package Util.Beans.Basic is pragma Preelaborate; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is limited interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return Util.Beans.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is limited interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is limited interface and Readonly_Bean; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. function Get_Count (From : List_Bean) return Natural is abstract; -- Set the current row index. Valid row indexes start at 1. procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is abstract; -- Get the element at the current row index. function Get_Row (From : List_Bean) return Util.Beans.Objects.Object is abstract; end Util.Beans.Basic;
----------------------------------------------------------------------- -- util-beans-basic -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; package Util.Beans.Basic is pragma Preelaborate; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is limited interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- 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 Readonly_Bean; Name : in String) return Util.Beans.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is limited interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in Util.Beans.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is limited interface and Readonly_Bean; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. function Get_Count (From : in List_Bean) return Natural is abstract; -- Set the current row index. Valid row indexes start at 1. procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is abstract; -- Get the element at the current row index. function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is abstract; end Util.Beans.Basic;
Update the header and fix general style
Update the header and fix general style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3c20b464e7cb5e35c591ea3c5eabe038b2ae72ce
src/wiki-nodes-lists.adb
src/wiki-nodes-lists.adb
----------------------------------------------------------------------- -- wiki-nodes-lists -- Wiki Document Internal representation -- Copyright (C) 2016, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Nodes.Lists is -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value, Node); end Append; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Accessor; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- ------------------------------ -- Returns True if the list reference is empty. -- ------------------------------ function Is_Empty (List : in Node_List_Ref) return Boolean is begin return List.Is_Null; end Is_Empty; -- ------------------------------ -- Get the number of nodes in the list. -- ------------------------------ function Length (List : in Node_List_Ref) return Natural is begin if List.Is_Null then return 0; else return List.Value.Length; end if; end Length; end Wiki.Nodes.Lists;
----------------------------------------------------------------------- -- wiki-nodes-lists -- Wiki Document Internal representation -- Copyright (C) 2016, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Nodes.Lists is -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value, Node); end Append; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Accessor; Process : not null access procedure (Node : in Node_Type)) is Block : access Node_List_Block := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- ------------------------------ -- Returns True if the list reference is empty. -- ------------------------------ function Is_Empty (List : in Node_List_Ref) return Boolean is begin return List.Is_Null; end Is_Empty; -- ------------------------------ -- Get the number of nodes in the list. -- ------------------------------ function Length (List : in Node_List_Ref) return Natural is begin if List.Is_Null then return 0; else return List.Value.Length; end if; end Length; end Wiki.Nodes.Lists;
Fix compilation issue with gcc 5
Fix compilation issue with gcc 5
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
003e788e9b89093210b3f54095825e2f2a581c4d
regtests/util-locales-tests.adb
regtests/util-locales-tests.adb
----------------------------------------------------------------------- -- locales.tests -- Unit tests for locales -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Locales.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Locales.Get_Locale", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Language", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Country", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Variant", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Hash", Test_Hash_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.=", Test_Compare_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Locales", Test_Get_Locales'Access); end Add_Tests; procedure Test_Get_Locale (T : in out Test) is Loc : Locale; begin Loc := Get_Locale ("en"); Assert_Equals (T, "en", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant"); Loc := Get_Locale ("ja", "JP", "JP"); Assert_Equals (T, "ja", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "JP", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "JP", Get_Variant (Loc), "Invalid variant"); Loc := Get_Locale ("no", "NO", "NY"); Assert_Equals (T, "no", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "NO", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "NY", Get_Variant (Loc), "Invalid variant"); end Test_Get_Locale; procedure Test_Hash_Locale (T : in out Test) is use type Ada.Containers.Hash_Type; begin T.Assert (Hash (FRANCE) /= Hash (FRENCH), "Hash should be different"); T.Assert (Hash (FRANCE) /= Hash (ENGLISH), "Hash should be different"); T.Assert (Hash (FRENCH) /= Hash (ENGLISH), "Hash should be different"); end Test_Hash_Locale; procedure Test_Compare_Locale (T : in out Test) is begin T.Assert (FRANCE /= FRENCH, "Equality"); T.Assert (FRANCE = FRANCE, "Equality"); T.Assert (FRANCE = Get_Locale ("fr", "FR"), "Equality"); T.Assert (FRANCE /= ENGLISH, "Equality"); T.Assert (FRENCH /= ENGLISH, "Equaliy"); end Test_Compare_Locale; procedure Test_Get_Locales (T : in out Test) is begin for I in Locales'Range loop declare Language : constant String := Get_Language (Locales (I)); Country : constant String := Get_Country (Locales (I)); Variant : constant String := Get_Variant (Locales (I)); Loc : constant Locale := Get_Locale (Language, Country, Variant); Name : constant String := To_String (Loc); begin T.Assert (Loc = Locales (I), "Invalid locale at " & Positive'Image (I) & " " & Loc.all); if Variant'Length > 0 then T.Assert (Name, Language & "_" & Country & "_" & Variant, "Invalid To_String"); elsif Country'Length > 0 then T.Assert (Name, Language & "_" & Country, "Invalid To_String"); else T.Assert (Name, Language, "Invalid To_String"); end if; end; end loop; end Test_Get_Locales; end Util.Locales.Tests;
----------------------------------------------------------------------- -- locales.tests -- Unit tests for locales -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; package body Util.Locales.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Locales.Get_Locale", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Language", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Country", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Get_Variant", Test_Get_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Hash", Test_Hash_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.=", Test_Compare_Locale'Access); Caller.Add_Test (Suite, "Test Util.Locales.Locales", Test_Get_Locales'Access); end Add_Tests; procedure Test_Get_Locale (T : in out Test) is Loc : Locale; begin Loc := Get_Locale ("en"); Assert_Equals (T, "en", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "", Get_Variant (Loc), "Invalid variant"); Loc := Get_Locale ("ja", "JP", "JP"); Assert_Equals (T, "ja", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "JP", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "JP", Get_Variant (Loc), "Invalid variant"); Loc := Get_Locale ("no", "NO", "NY"); Assert_Equals (T, "no", Get_Language (Loc), "Invalid language"); Assert_Equals (T, "NO", Get_Country (Loc), "Invalid country"); Assert_Equals (T, "NY", Get_Variant (Loc), "Invalid variant"); end Test_Get_Locale; procedure Test_Hash_Locale (T : in out Test) is use type Ada.Containers.Hash_Type; begin T.Assert (Hash (FRANCE) /= Hash (FRENCH), "Hash should be different"); T.Assert (Hash (FRANCE) /= Hash (ENGLISH), "Hash should be different"); T.Assert (Hash (FRENCH) /= Hash (ENGLISH), "Hash should be different"); end Test_Hash_Locale; procedure Test_Compare_Locale (T : in out Test) is begin T.Assert (FRANCE /= FRENCH, "Equality"); T.Assert (FRANCE = FRANCE, "Equality"); T.Assert (FRANCE = Get_Locale ("fr", "FR"), "Equality"); T.Assert (FRANCE /= ENGLISH, "Equality"); T.Assert (FRENCH /= ENGLISH, "Equaliy"); end Test_Compare_Locale; procedure Test_Get_Locales (T : in out Test) is begin for I in Locales'Range loop declare Language : constant String := Get_Language (Locales (I)); Country : constant String := Get_Country (Locales (I)); Variant : constant String := Get_Variant (Locales (I)); Loc : constant Locale := Get_Locale (Language, Country, Variant); Name : constant String := To_String (Loc); begin T.Assert (Loc = Locales (I), "Invalid locale at " & Positive'Image (I) & " " & Loc.all); if Variant'Length > 0 then Assert (T, Name, Language & "_" & Country & "_" & Variant, "Invalid To_String"); elsif Country'Length > 0 then Assert (T, Name, Language & "_" & Country, "Invalid To_String"); else Assert (T, Name, Language, "Invalid To_String"); end if; end; end loop; end Test_Get_Locales; end Util.Locales.Tests;
Fix compilation issue with GNAT 2011
Fix compilation issue with GNAT 2011
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
81a93088e7a1759233742d7f0a0770d472766363
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Containers.Vectors; with Wiki.Documents; with Wiki.Attributes; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; package Wide_Wide_String_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Unbounded_Wide_Wide_String); subtype Wide_Wide_String_Vector is Wide_Wide_String_Vectors.Vector; subtype Wide_Wide_String_Cursor is Wide_Wide_String_Vectors.Cursor; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; Html_Stack : Wide_Wide_String_Vector; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); procedure Start_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Flush the pending HTML stack elements. procedure Flush_Stack (P : in out Parser); end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; -- == Wiki Parsers == -- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats. -- The parser works with the <b>Document_Reader</b> interface type which defines several -- procedures that are called by the parser when the wiki text is scanned. package Wiki.Parsers is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax_Type is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- A mix of the above SYNTAX_MIX); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- specified in <b>Syntax</b> and invoke the document reader procedures defined -- by <b>into</b>. procedure Parse (Into : in Wiki.Documents.Document_Reader_Access; Text : in Wide_Wide_String; Syntax : in Wiki_Syntax_Type := SYNTAX_MIX); private use Ada.Strings.Wide_Wide_Unbounded; HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); type Input is interface; type Input_Access is access all Input'Class; procedure Read_Char (From : in out Input; Token : out Wide_Wide_Character; Eof : out Boolean) is abstract; type Parser is limited record Pending : Wide_Wide_Character; Has_Pending : Boolean; Document : Wiki.Documents.Document_Reader_Access; Format : Wiki.Documents.Format_Map; Text : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Token : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Empty_Line : Boolean := True; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; Need_Paragraph : Boolean := True; Link_Double_Bracket : Boolean := False; Is_Dotclear : Boolean := False; Header_Offset : Integer := 0; Quote_Level : Natural := 0; Escape_Char : Wide_Wide_Character; List_Level : Natural := 0; Reader : Input_Access := null; Attributes : Wiki.Attributes.Attribute_List_Type; end record; type Parser_Handler is access procedure (P : in out Parser; Token : in Wide_Wide_Character); type Parser_Table is array (0 .. 127) of Parser_Handler; type Parser_Table_Access is access Parser_Table; -- Peek the next character from the wiki text buffer. procedure Peek (P : in out Parser; Token : out Wide_Wide_Character); -- Put back the character so that it will be returned by the next call to Peek. procedure Put_Back (P : in out Parser; Token : in Wide_Wide_Character); -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser); procedure Start_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type); procedure End_Element (P : in out Parser; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); end Wiki.Parsers;
Remove the Html_Stack (must use the HTML filter instead)
Remove the Html_Stack (must use the HTML filter instead)
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
3d94039202b962fd8a1ad0f193e7d7f0eba20cb3
tests/natools-s_expressions-parsers-tests.adb
tests/natools-s_expressions-parsers-tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Lockable.Tests; with Natools.S_Expressions.Printers; with Natools.S_Expressions.Test_Tools; package body Natools.S_Expressions.Parsers.Tests is generic Name : String; Source, Expected : Atom; procedure Blackbox_Test (Report : in out NT.Reporter'Class); -- Perform a simple blackbox test, feeding Source to a new parser -- plugged on a canonical printer and comparing with Expected. ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Blackbox_Test (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (Name); begin declare Input, Output : aliased Test_Tools.Memory_Stream; Printer : Printers.Canonical (Output'Access); Parser : Parsers.Stream_Parser (Input'Access); begin Output.Set_Expected (Expected); Input.Set_Data (Source); Parser.Next; Printers.Transfer (Parser, Printer); Output.Check_Stream (Test); end; exception when Error : others => Test.Report_Exception (Error); end Blackbox_Test; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Canonical_Encoding (Report); Atom_Encodings (Report); Base64_Subexpression (Report); Special_Subexpression (Report); Nested_Subpexression (Report); Number_Prefixes (Report); Quoted_Escapes (Report); Lockable_Interface (Report); Reset (Report); Locked_Next (Report); Memory_Parser (Report); end All_Tests; ----------------------- -- Inidividual Tests -- ----------------------- procedure Atom_Encodings (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Basic atom encodings", Source => To_Atom ("17:Verbatim encoding" & """Quoted\040string""" & "#48657861646563696d616c2064756d70#" & "token " & "|QmFzZS02NCBlbmNvZGluZw==|"), Expected => To_Atom ("17:Verbatim encoding" & "13:Quoted string" & "16:Hexadecimal dump" & "5:token" & "16:Base-64 encoding")); begin Test (Report); end Atom_Encodings; procedure Canonical_Encoding (Report : in out NT.Reporter'Class) is Sample_Image : constant String := "3:The(5:quick((5:brown3:fox)5:jumps))9:over3:the()4:lazy0:3:dog"; procedure Test is new Blackbox_Test (Name => "Canonical encoding", Source => To_Atom (Sample_Image), Expected => To_Atom (Sample_Image)); begin Test (Report); end Canonical_Encoding; procedure Base64_Subexpression (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Base-64 subexpression", Source => To_Atom ("head({KDc6c3VibGlzdCk1OnRva2Vu})""tail"""), Expected => To_Atom ("4:head((7:sublist)5:token)4:tail")); begin Test (Report); end Base64_Subexpression; procedure Lockable_Interface (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Lockable.Descriptor interface"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (Lockable.Tests.Test_Expression); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Lockable.Tests.Test_Interface (Test, Parser); end; exception when Error : others => Test.Report_Exception (Error); end Lockable_Interface; procedure Locked_Next (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Next on locked parser"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); Lock_State : Lockable.Lock_State; begin Input.Set_Data (To_Atom ("(command (subcommand arg (arg list)))0:")); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("command"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("subcommand"), 2); Parser.Lock (Lock_State); Test_Tools.Test_Atom_Accessors (Test, Parser, To_Atom ("subcommand"), 0); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 0); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); Parser.Unlock (Lock_State); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0); Test_Tools.Next_And_Check (Test, Parser, Null_Atom, 0); end; exception when Error : others => Test.Report_Exception (Error); end Locked_Next; procedure Memory_Parser (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Memory-backed parser"); begin declare Parser : Parsers.Memory_Parser := Create_From_String ("(command (subcommand arg (arg list)))0:"); begin Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("command"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("subcommand"), 2); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 2); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 3); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 3); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 3); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 2); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 1); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0); Test_Tools.Next_And_Check (Test, Parser, Null_Atom, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); end; exception when Error : others => Test.Report_Exception (Error); end Memory_Parser; procedure Nested_Subpexression (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Nested base-64 subepxressions", Source => To_Atom ("(5:begin" & "{KG5lc3RlZCB7S0dSbFpYQWdjR0Y1Ykc5aFpDaz19KQ==}" & "end)"), Expected => To_Atom ("(5:begin" & "(6:nested(4:deep7:payload))" & "3:end)")); begin Test (Report); end Nested_Subpexression; procedure Number_Prefixes (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Number prefixes", Source => To_Atom ("8:verbatim" & "(valid 6""quoted"" 11#68657861646563696d616c#" & " 7|YmFzZS02NA==| 9{NzpleHByLTY0})" & "(undefined 42 10% 123() 10)" & "(invalid 10""quoted"" 3#68657861646563696d616c#" & " 75|YmFzZS02NA==| 1{NzpleHByLTY0})"), Expected => To_Atom ("8:verbatim" & "(5:valid6:quoted11:hexadecimal7:base-647:expr-64)" & "(9:undefined2:423:10%3:123()2:10)" & "(7:invalid6:quoted11:hexadecimal7:base-647:expr-64)")); begin Test (Report); end Number_Prefixes; procedure Quoted_Escapes (Report : in out NT.Reporter'Class) is CR : constant Character := Character'Val (13); LF : constant Character := Character'Val (10); procedure Test is new Blackbox_Test (Name => "Escapes in quoted encoding", Source => To_Atom ("(single-letters ""\b\t\n\v\f\r\\\k"")" & "(newlines ""head\" & CR & "tail"" ""head\" & LF & "tail""" & " ""head\" & CR & LF & "tail"" ""head\" & LF & CR & "tail"")" & "(octal ""head\040\04\xtail"")" & "(hexadecimal ""head\x20\x2a\x2D\x2gtail"")" & "(special ""\x""1:"")"), Expected => To_Atom ("(14:single-letters9:" & Character'Val (8) & Character'Val (9) & Character'Val (10) & Character'Val (11) & Character'Val (12) & Character'Val (13) & "\\k)" & "(8:newlines8:headtail8:headtail8:headtail8:headtail)" & "(5:octal14:head \04\xtail)" & "(11:hexadecimal15:head *-\x2gtail)" & "(7:special2:\x1:"")")); begin Test (Report); end Quoted_Escapes; procedure Reset (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parser reset"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); Empty : Parsers.Stream_Parser (Input'Access); use type Atom_Buffers.Atom_Buffer; use type Lockable.Lock_Stack; begin Input.Write (To_Atom ("(begin(first second")); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("begin"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("first"), 2); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 2); Parser.Reset (Hard => False); Input.Write (To_Atom ("other(new list)end")); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("other"), 0); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("new"), 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0); Parser.Reset (Hard => True); if Parser.Internal /= Empty.Internal or else Parser.Next_Event /= Empty.Next_Event or else Parser.Latest /= Empty.Latest or else Parser.Pending.Capacity /= 0 or else Parser.Buffer.Capacity /= 0 or else Parser.Level /= Empty.Level or else Parser.Lock_Stack /= Empty.Lock_Stack or else Parser.Locked /= Empty.Locked then Test.Fail ("Parser after hard reset is not empty"); end if; end; exception when Error : others => Test.Report_Exception (Error); end Reset; procedure Special_Subexpression (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Special base-64 subexpression", Source => To_Atom ("(begin " & "{aGlkZGVuLWVuZCkoaGlkZGVuLWJlZ2lu}" & " end)" & "({MTY6b3ZlcmZsb3dpbmc=} atom)"), Expected => To_Atom ("(5:begin" & "10:hidden-end)(12:hidden-begin" & "3:end)" & "(16:overflowing atom)")); begin Test (Report); end Special_Subexpression; end Natools.S_Expressions.Parsers.Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Lockable.Tests; with Natools.S_Expressions.Printers; with Natools.S_Expressions.Test_Tools; package body Natools.S_Expressions.Parsers.Tests is generic Name : String; Source, Expected : Atom; procedure Blackbox_Test (Report : in out NT.Reporter'Class); -- Perform a simple blackbox test, feeding Source to a new parser -- plugged on a canonical printer and comparing with Expected. ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Blackbox_Test (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item (Name); begin declare Input, Output : aliased Test_Tools.Memory_Stream; Printer : Printers.Canonical (Output'Access); Parser : Parsers.Stream_Parser (Input'Access); begin Output.Set_Expected (Expected); Input.Set_Data (Source); Parser.Next; Printers.Transfer (Parser, Printer); Output.Check_Stream (Test); end; exception when Error : others => Test.Report_Exception (Error); end Blackbox_Test; ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Canonical_Encoding (Report); Atom_Encodings (Report); Base64_Subexpression (Report); Special_Subexpression (Report); Nested_Subpexression (Report); Number_Prefixes (Report); Quoted_Escapes (Report); Lockable_Interface (Report); Reset (Report); Locked_Next (Report); Memory_Parser (Report); end All_Tests; ----------------------- -- Inidividual Tests -- ----------------------- procedure Atom_Encodings (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Basic atom encodings", Source => To_Atom ("17:Verbatim encoding" & """Quoted\040string""" & "#48657861646563696d616c2064756d70#" & "token " & "|QmFzZS02NCBlbmNvZGluZw==|"), Expected => To_Atom ("17:Verbatim encoding" & "13:Quoted string" & "16:Hexadecimal dump" & "5:token" & "16:Base-64 encoding")); begin Test (Report); end Atom_Encodings; procedure Base64_Subexpression (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Base-64 subexpression", Source => To_Atom ("head({KDc6c3VibGlzdCk1OnRva2Vu})""tail"""), Expected => To_Atom ("4:head((7:sublist)5:token)4:tail")); begin Test (Report); end Base64_Subexpression; procedure Canonical_Encoding (Report : in out NT.Reporter'Class) is Sample_Image : constant String := "3:The(5:quick((5:brown3:fox)5:jumps))9:over3:the()4:lazy0:3:dog"; procedure Test is new Blackbox_Test (Name => "Canonical encoding", Source => To_Atom (Sample_Image), Expected => To_Atom (Sample_Image)); begin Test (Report); end Canonical_Encoding; procedure Lockable_Interface (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Lockable.Descriptor interface"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); begin Input.Set_Data (Lockable.Tests.Test_Expression); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Lockable.Tests.Test_Interface (Test, Parser); end; exception when Error : others => Test.Report_Exception (Error); end Lockable_Interface; procedure Locked_Next (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Next on locked parser"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); Lock_State : Lockable.Lock_State; begin Input.Set_Data (To_Atom ("(command (subcommand arg (arg list)))0:")); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("command"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("subcommand"), 2); Parser.Lock (Lock_State); Test_Tools.Test_Atom_Accessors (Test, Parser, To_Atom ("subcommand"), 0); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 0); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); Parser.Unlock (Lock_State); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0); Test_Tools.Next_And_Check (Test, Parser, Null_Atom, 0); end; exception when Error : others => Test.Report_Exception (Error); end Locked_Next; procedure Memory_Parser (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Memory-backed parser"); begin declare Parser : Parsers.Memory_Parser := Create_From_String ("(command (subcommand arg (arg list)))0:"); begin Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("command"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("subcommand"), 2); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 2); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 3); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("arg"), 3); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 3); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 2); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 1); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0); Test_Tools.Next_And_Check (Test, Parser, Null_Atom, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 0); end; exception when Error : others => Test.Report_Exception (Error); end Memory_Parser; procedure Nested_Subpexression (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Nested base-64 subepxressions", Source => To_Atom ("(5:begin" & "{KG5lc3RlZCB7S0dSbFpYQWdjR0Y1Ykc5aFpDaz19KQ==}" & "end)"), Expected => To_Atom ("(5:begin" & "(6:nested(4:deep7:payload))" & "3:end)")); begin Test (Report); end Nested_Subpexression; procedure Number_Prefixes (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Number prefixes", Source => To_Atom ("8:verbatim" & "(valid 6""quoted"" 11#68657861646563696d616c#" & " 7|YmFzZS02NA==| 9{NzpleHByLTY0})" & "(undefined 42 10% 123() 10)" & "(invalid 10""quoted"" 3#68657861646563696d616c#" & " 75|YmFzZS02NA==| 1{NzpleHByLTY0})"), Expected => To_Atom ("8:verbatim" & "(5:valid6:quoted11:hexadecimal7:base-647:expr-64)" & "(9:undefined2:423:10%3:123()2:10)" & "(7:invalid6:quoted11:hexadecimal7:base-647:expr-64)")); begin Test (Report); end Number_Prefixes; procedure Quoted_Escapes (Report : in out NT.Reporter'Class) is CR : constant Character := Character'Val (13); LF : constant Character := Character'Val (10); procedure Test is new Blackbox_Test (Name => "Escapes in quoted encoding", Source => To_Atom ("(single-letters ""\b\t\n\v\f\r\\\k"")" & "(newlines ""head\" & CR & "tail"" ""head\" & LF & "tail""" & " ""head\" & CR & LF & "tail"" ""head\" & LF & CR & "tail"")" & "(octal ""head\040\04\xtail"")" & "(hexadecimal ""head\x20\x2a\x2D\x2gtail"")" & "(special ""\x""1:"")"), Expected => To_Atom ("(14:single-letters9:" & Character'Val (8) & Character'Val (9) & Character'Val (10) & Character'Val (11) & Character'Val (12) & Character'Val (13) & "\\k)" & "(8:newlines8:headtail8:headtail8:headtail8:headtail)" & "(5:octal14:head \04\xtail)" & "(11:hexadecimal15:head *-\x2gtail)" & "(7:special2:\x1:"")")); begin Test (Report); end Quoted_Escapes; procedure Reset (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Parser reset"); begin declare Input : aliased Test_Tools.Memory_Stream; Parser : Parsers.Stream_Parser (Input'Access); Empty : Parsers.Stream_Parser (Input'Access); use type Atom_Buffers.Atom_Buffer; use type Lockable.Lock_Stack; begin Input.Write (To_Atom ("(begin(first second")); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("begin"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 2); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("first"), 2); Test_Tools.Next_And_Check (Test, Parser, Events.End_Of_Input, 2); Parser.Reset (Hard => False); Input.Write (To_Atom ("other(new list)end")); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("other"), 0); Test_Tools.Next_And_Check (Test, Parser, Events.Open_List, 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("new"), 1); Test_Tools.Next_And_Check (Test, Parser, To_Atom ("list"), 1); Test_Tools.Next_And_Check (Test, Parser, Events.Close_List, 0); Parser.Reset (Hard => True); if Parser.Internal /= Empty.Internal or else Parser.Next_Event /= Empty.Next_Event or else Parser.Latest /= Empty.Latest or else Parser.Pending.Capacity /= 0 or else Parser.Buffer.Capacity /= 0 or else Parser.Level /= Empty.Level or else Parser.Lock_Stack /= Empty.Lock_Stack or else Parser.Locked /= Empty.Locked then Test.Fail ("Parser after hard reset is not empty"); end if; end; exception when Error : others => Test.Report_Exception (Error); end Reset; procedure Special_Subexpression (Report : in out NT.Reporter'Class) is procedure Test is new Blackbox_Test (Name => "Special base-64 subexpression", Source => To_Atom ("(begin " & "{aGlkZGVuLWVuZCkoaGlkZGVuLWJlZ2lu}" & " end)" & "({MTY6b3ZlcmZsb3dpbmc=} atom)"), Expected => To_Atom ("(5:begin" & "10:hidden-end)(12:hidden-begin" & "3:end)" & "(16:overflowing atom)")); begin Test (Report); end Special_Subexpression; end Natools.S_Expressions.Parsers.Tests;
fix alphabetical ordering of tests
s_expressions-parsers-tests: fix alphabetical ordering of tests
Ada
isc
faelys/natools
68f4bc66161462324f64e1f31a6ccd7a60f64fb4
tools/druss-commands.ads
tools/druss-commands.ads
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_WAN_IP, F_INTERNET, F_VOIP, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type); procedure Initialize; end Druss.Commands;
----------------------------------------------------------------------- -- druss-commands -- Commands available for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Commands.Drivers; with Util.Commands.Consoles; with Util.Commands.Consoles.Text; with Druss.Gateways; package Druss.Commands is -- The list of fields that are printed on the console. type Field_Type is (F_IP_ADDR, F_WAN_IP, F_INTERNET, F_VOIP, F_WIFI, F_WIFI5, F_ACCESS_CONTROL, F_DYNDNS, F_DEVICES, F_COUNT, F_BOOL, F_CHANNEL, F_PROTOCOL, F_ENCRYPTION, F_SSID); -- The type of notice that are reported. type Notice_Type is (N_HELP, N_INFO); -- Make the generic abstract console interface. package Consoles is new Util.Commands.Consoles (Field_Type => Field_Type, Notice_Type => Notice_Type); -- And the text console to write on stdout (a Gtk console could be done someday). package Text_Consoles is new Consoles.Text; type Context_Type is limited record Gateways : Druss.Gateways.Gateway_Vector; Console : Consoles.Console_Access; end record; package Drivers is new Util.Commands.Drivers (Context_Type => Context_Type, Driver_Name => "druss-drivers"); subtype Argument_List is Util.Commands.Argument_List; Driver : Drivers.Driver_Type; procedure Gateway_Command (Command : in Drivers.Command_Type'Class; Args : in Util.Commands.Argument_List'Class; Arg_Pos : in Positive; Process : access procedure (Gateway : in out Gateways.Gateway_Type; Param : in String); Context : in out Context_Type); procedure Initialize; -- Print the bbox API status. procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String); end Druss.Commands;
Declare the Print_Status procedure
Declare the Print_Status procedure
Ada
apache-2.0
stcarrez/bbox-ada-api