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
2eb1e5450d37aa3d5bd2b5845082208a3e270d8f
src/mysql/mysql-my_list.ads
src/mysql/mysql-my_list.ads
with Interfaces.C; use Interfaces.C; with System; package Mysql.My_list is -- arg-macro: function list_rest (a) -- return (a).next; -- arg-macro: function list_push (a, b) -- return a):=list_cons((b),(a); -- Copyright (C) 2000 MySQL AB -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 2 of the License. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- /usr/include/mysql/my_list.h:24:19 type st_list is record prev : access st_list; next : access st_list; data : System.Address; end record; pragma Convention (C, st_list); subtype LIST is st_list; type List_Walk_Action is access function (arg1 : System.Address; arg2 : System.Address) return int; function list_add (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_add, "list_add"); function list_delete (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_delete, "list_delete"); function list_cons (arg1 : System.Address; arg2 : access st_list) return access st_list; pragma Import (C, list_cons, "list_cons"); function list_reverse (arg1 : access st_list) return access st_list; pragma Import (C, list_reverse, "list_reverse"); procedure list_free (arg1 : access st_list; arg2 : unsigned); pragma Import (C, list_free, "list_free"); function list_length (arg1 : access st_list) return unsigned; pragma Import (C, list_length, "list_length"); end Mysql.My_list;
with Interfaces.C; use Interfaces.C; with System; package Mysql.My_list is pragma Pure; -- arg-macro: function list_rest (a) -- return (a).next; -- arg-macro: function list_push (a, b) -- return a):=list_cons((b),(a); -- Copyright (C) 2000 MySQL AB -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 2 of the License. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- /usr/include/mysql/my_list.h:24:19 type st_list is record prev : access st_list; next : access st_list; data : System.Address; end record; pragma Convention (C, st_list); subtype LIST is st_list; type List_Walk_Action is access function (arg1 : System.Address; arg2 : System.Address) return int; function list_add (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_add, "list_add"); function list_delete (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_delete, "list_delete"); function list_cons (arg1 : System.Address; arg2 : access st_list) return access st_list; pragma Import (C, list_cons, "list_cons"); function list_reverse (arg1 : access st_list) return access st_list; pragma Import (C, list_reverse, "list_reverse"); procedure list_free (arg1 : access st_list; arg2 : unsigned); pragma Import (C, list_free, "list_free"); function list_length (arg1 : access st_list) return unsigned; pragma Import (C, list_length, "list_length"); end Mysql.My_list;
Make the package Pure
Make the package Pure
Ada
apache-2.0
Letractively/ada-ado
b7284564ed543d63b6d6135ca9c1acf5103abbf5
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
stcarrez/ada-security
305529b6da3c626722f8447464decfe3b24f0bc0
awa/src/awa-users-beans.ads
awa/src/awa-users-beans.ads
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Ada.Strings.Unbounded; with AWA.Users.Services; with AWA.Users.Modules; with AWA.Users.Principals; package AWA.Users.Beans is use Ada.Strings.Unbounded; type Authenticate_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Users.Modules.User_Module_Access := null; Manager : AWA.Users.Services.User_Service_Access := null; Email : Unbounded_String; Password : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Access_Key : Unbounded_String; end record; -- Attributes exposed by the <b>Authenticate_Bean</b> through Get_Value. EMAIL_ATTR : constant String := "email"; PASSWORD_ATTR : constant String := "password"; FIRST_NAME_ATTR : constant String := "firstName"; LAST_NAME_ATTR : constant String := "lastName"; KEY_ATTR : constant String := "key"; type Authenticate_Bean_Access is access all Authenticate_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; procedure Set_Session_Principal (Data : in Authenticate_Bean; Principal : in AWA.Users.Principals.Principal_Access); procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean; Principal : in AWA.Users.Principals.Principal_Access); -- Action to register a user procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Action to verify the user after the registration procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Action to trigger the lost password email process. procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Action to validate the reset password key and set a new password. procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Action to authenticate a user (password authentication). procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Logout the user and closes the session. procedure Logout_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Create an authenticate bean. function Create_Authenticate_Bean (Module : in AWA.Users.Modules.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Current user -- ------------------------------ -- The <b>Current_User_Bean</b> provides information about the current user. -- It relies on the <b>AWA.Services.Contexts</b> to identify the current user -- and return information about him/her. type Current_User_Bean is new Util.Beans.Basic.Readonly_Bean with null record; type Current_User_Bean_Access is access all Current_User_Bean'Class; -- Attributes exposed by <b>Current_User_Bean</b> IS_LOGGED_ATTR : constant String := "isLogged"; USER_EMAIL_ATTR : constant String := "email"; USER_NAME_ATTR : constant String := "name"; USER_ID_ATTR : constant String := "id"; -- Get the value identified by the name. The following names are recognized: -- o isLogged Boolean True if a user is logged -- o name String The user name -- o email String The user email address -- o id Long The user identifier overriding function Get_Value (From : in Current_User_Bean; Name : in String) return Util.Beans.Objects.Object; -- Create the current user bean. function Create_Current_User_Bean (Module : in AWA.Users.Modules.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Users.Beans;
----------------------------------------------------------------------- -- awa-users-beans -- ASF Beans for user module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with Ada.Strings.Unbounded; with AWA.Users.Services; with AWA.Users.Modules; with AWA.Users.Principals; package AWA.Users.Beans is use Ada.Strings.Unbounded; type Authenticate_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Users.Modules.User_Module_Access := null; Manager : AWA.Users.Services.User_Service_Access := null; Email : Unbounded_String; Password : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Access_Key : Unbounded_String; end record; -- Attributes exposed by the <b>Authenticate_Bean</b> through Get_Value. EMAIL_ATTR : constant String := "email"; PASSWORD_ATTR : constant String := "password"; FIRST_NAME_ATTR : constant String := "firstName"; LAST_NAME_ATTR : constant String := "lastName"; KEY_ATTR : constant String := "key"; type Authenticate_Bean_Access is access all Authenticate_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Authenticate_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Authenticate_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Authenticate_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; procedure Set_Session_Principal (Data : in Authenticate_Bean; Principal : in AWA.Users.Principals.Principal_Access); procedure Set_Authenticate_Cookie (Data : in out Authenticate_Bean; Principal : in AWA.Users.Principals.Principal_Access); -- Action to register a user procedure Register_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Action to verify the user after the registration procedure Verify_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Action to trigger the lost password email process. procedure Lost_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Action to validate the reset password key and set a new password. procedure Reset_Password (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Action to authenticate a user (password authentication). procedure Authenticate_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Logout the user and closes the session. procedure Logout_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); procedure Load_User (Data : in out Authenticate_Bean; Outcome : in out Unbounded_String); -- Create an authenticate bean. function Create_Authenticate_Bean (Module : in AWA.Users.Modules.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Current user -- ------------------------------ -- The <b>Current_User_Bean</b> provides information about the current user. -- It relies on the <b>AWA.Services.Contexts</b> to identify the current user -- and return information about him/her. type Current_User_Bean is new Util.Beans.Basic.Readonly_Bean with null record; type Current_User_Bean_Access is access all Current_User_Bean'Class; -- Attributes exposed by <b>Current_User_Bean</b> IS_LOGGED_ATTR : constant String := "isLogged"; USER_EMAIL_ATTR : constant String := "email"; USER_NAME_ATTR : constant String := "name"; USER_ID_ATTR : constant String := "id"; -- Get the value identified by the name. The following names are recognized: -- o isLogged Boolean True if a user is logged -- o name String The user name -- o email String The user email address -- o id Long The user identifier overriding function Get_Value (From : in Current_User_Bean; Name : in String) return Util.Beans.Objects.Object; -- Create the current user bean. function Create_Current_User_Bean (Module : in AWA.Users.Modules.User_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Users.Beans;
Declare the Load_User procedure
Declare the Load_User procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
910c23eb2df76e3aeae73cb42bb91375201a26c3
src/asf-components-widgets-inputs.adb
src/asf-components-widgets-inputs.adb
----------------------------------------------------------------------- -- asf-components-widgets-inputs -- Input widget components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with ASF.Models.Selects; with ASF.Components.Base; with ASF.Components.Utils; with ASF.Components.Html.Messages; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Vectors; with Util.Strings.Transforms; with Util.Beans.Objects; package body ASF.Components.Widgets.Inputs is -- ------------------------------ -- Render the input field title. -- ------------------------------ procedure Render_Title (UI : in UIInput; Name : in String; Writer : in Response_Writer_Access; Context : in out Faces_Context'Class) is Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title"); begin Writer.Start_Element ("dt"); Writer.Start_Element ("label"); Writer.Write_Attribute ("for", Name); Writer.Write_Text (Title); Writer.End_Element ("label"); Writer.End_Element ("dt"); end Render_Title; -- ------------------------------ -- 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 UIInput; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); Style : constant String := UI.Get_Attribute ("styleClass", Context); begin Writer.Start_Element ("dl"); Writer.Write_Attribute ("id", Id); if ASF.Applications.Messages.Vectors.Has_Element (Messages) then Writer.Write_Attribute ("class", Style & " asf-error"); elsif Style'Length > 0 then Writer.Write_Attribute ("class", Style); end if; UI.Render_Title (Id, Writer, Context); Writer.Start_Element ("dd"); UI.Render_Input (Context, Write_Id => False); end; end Encode_Begin; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIInput; Context : in out Faces_Context'Class) is use ASF.Components.Html.Messages; begin if not UI.Is_Rendered (Context) then return; end if; -- Render the error message associated with the input field. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); begin if ASF.Applications.Messages.Vectors.Has_Element (Messages) then Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages), SPAN_NO_STYLE, False, True, Context); end if; Writer.End_Element ("dd"); Writer.End_Element ("dl"); end; end Encode_End; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIComplete; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; -- Render the autocomplete script and finish the input component. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Queue_Script ("$('#"); Writer.Queue_Script (Id); Writer.Queue_Script (" input').complete({"); Writer.Queue_Script ("});"); UIInput (UI).Encode_End (Context); end; end Encode_End; overriding procedure Process_Decodes (UI : in out UIComplete; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Id : constant String := To_String (UI.Get_Client_Id); Val : constant String := Context.Get_Parameter (Id & ".match"); begin if Val'Length > 0 then UI.Match_Value := Util.Beans.Objects.To_Object (Val); else ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context); end if; end; end Process_Decodes; procedure Render_List (UI : in UIComplete; Match : in String; Context : in out Faces_Context'Class) is use type Util.Beans.Basic.List_Bean_Access; List : constant Util.Beans.Basic.List_Bean_Access := ASF.Components.Utils.Get_List_Bean (UI, "autocomplete", Context); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Need_Comma : Boolean := False; Count : Natural; procedure Render_Item (Label : in String) is Result : Ada.Strings.Unbounded.Unbounded_String; begin if Match'Length = 0 or else (Match'Length <= Label'Length and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then if Need_Comma then Writer.Write (","); end if; Writer.Write ('"'); Util.Strings.Transforms.Escape_Java (Content => Label, Into => Result); Writer.Write (Result); Writer.Write ('"'); Need_Comma := True; end if; end Render_Item; begin Writer.Write ('['); if List /= null then Count := List.Get_Count; if List.all in ASF.Models.Selects.Select_Item_List'Class then declare S : access ASF.Models.Selects.Select_Item_List'Class := ASF.Models.Selects.Select_Item_List'Class (List.all)'Access; begin for I in 1 .. Count loop Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label)); end loop; end; else for I in 1 .. Count loop List.Set_Row_Index (I); declare Value : constant Util.Beans.Objects.Object := List.Get_Row; Label : constant String := Util.Beans.Objects.To_String (Value); begin Render_Item (Label); end; end loop; end if; end if; Writer.Write (']'); end Render_List; overriding procedure Process_Updates (UI : in out UIComplete; Context : in out Faces_Context'Class) is begin if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then declare Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match"); ME : EL.Expressions.Method_Expression; begin if Value /= null then declare VE : constant EL.Expressions.Value_Expression := ASF.Views.Nodes.Get_Value_Expression (Value.all); begin VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all); end; end if; -- Post an event on this component to trigger the rendering of the completion -- list as part of an application/json output. The rendering is made by Broadcast. ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => ME); end; else ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context); end if; -- exception -- when E : others => -- UI.Is_Valid := False; -- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context); -- Log.Info (Utils.Get_Line_Info (UI) -- & ": Exception raised when updating value {0} for component {1}: {2}", -- EL.Objects.To_String (UI.Submitted_Value), -- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E)); end Process_Updates; -- ------------------------------ -- 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 UIComplete; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class) is pragma Unreferenced (Event); Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value); begin Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8"); UI.Render_List (Match, Context); Context.Response_Completed; end Broadcast; end ASF.Components.Widgets.Inputs;
----------------------------------------------------------------------- -- asf-components-widgets-inputs -- Input widget components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Characters.Conversions; with ASF.Models.Selects; with ASF.Components.Base; with ASF.Components.Utils; with ASF.Components.Html.Messages; with ASF.Events.Faces.Actions; with ASF.Applications.Messages.Vectors; with Util.Strings.Transforms; with Util.Beans.Objects; package body ASF.Components.Widgets.Inputs is -- ------------------------------ -- Render the input field title. -- ------------------------------ procedure Render_Title (UI : in UIInput; Name : in String; Writer : in Response_Writer_Access; Context : in out Faces_Context'Class) is Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title"); begin Writer.Start_Element ("dt"); Writer.Start_Element ("label"); Writer.Write_Attribute ("for", Name); Writer.Write_Text (Title); Writer.End_Element ("label"); Writer.End_Element ("dt"); end Render_Title; -- ------------------------------ -- 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 UIInput; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); Style : constant String := UI.Get_Attribute ("styleClass", Context); begin Writer.Start_Element ("dl"); Writer.Write_Attribute ("id", Id); if ASF.Applications.Messages.Vectors.Has_Element (Messages) then Writer.Write_Attribute ("class", Style & " asf-error"); elsif Style'Length > 0 then Writer.Write_Attribute ("class", Style); end if; UI.Render_Title (Id, Writer, Context); Writer.Start_Element ("dd"); UI.Render_Input (Context, Write_Id => False); end; end Encode_Begin; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIInput; Context : in out Faces_Context'Class) is use ASF.Components.Html.Messages; begin if not UI.Is_Rendered (Context) then return; end if; -- Render the error message associated with the input field. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); begin if ASF.Applications.Messages.Vectors.Has_Element (Messages) then Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages), SPAN_NO_STYLE, False, True, Context); end if; Writer.End_Element ("dd"); Writer.End_Element ("dl"); end; end Encode_End; -- ------------------------------ -- Render the end of the input component. Closes the DL/DD list. -- ------------------------------ overriding procedure Encode_End (UI : in UIComplete; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; -- Render the autocomplete script and finish the input component. declare Id : constant String := To_String (UI.Get_Client_Id); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Queue_Script ("$('#"); Writer.Queue_Script (Id); Writer.Queue_Script (" input').complete({"); Writer.Queue_Script ("});"); UIInput (UI).Encode_End (Context); end; end Encode_End; overriding procedure Process_Decodes (UI : in out UIComplete; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Id : constant String := To_String (UI.Get_Client_Id); Val : constant String := Context.Get_Parameter (Id & ".match"); begin if Val'Length > 0 then UI.Match_Value := Util.Beans.Objects.To_Object (Val); else ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context); end if; end; end Process_Decodes; procedure Render_List (UI : in UIComplete; Match : in String; Context : in out Faces_Context'Class) is use type Util.Beans.Basic.List_Bean_Access; List : constant Util.Beans.Basic.List_Bean_Access := ASF.Components.Utils.Get_List_Bean (UI, "autocompleteList", Context); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Need_Comma : Boolean := False; Count : Natural; procedure Render_Item (Label : in String) is Result : Ada.Strings.Unbounded.Unbounded_String; begin if Match'Length = 0 or else (Match'Length <= Label'Length and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then if Need_Comma then Writer.Write (","); end if; Writer.Write ('"'); Util.Strings.Transforms.Escape_Java (Content => Label, Into => Result); Writer.Write (Result); Writer.Write ('"'); Need_Comma := True; end if; end Render_Item; begin Writer.Write ('['); if List /= null then Count := List.Get_Count; if List.all in ASF.Models.Selects.Select_Item_List'Class then declare S : constant access ASF.Models.Selects.Select_Item_List'Class := ASF.Models.Selects.Select_Item_List'Class (List.all)'Access; begin for I in 1 .. Count loop Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label)); end loop; end; else for I in 1 .. Count loop List.Set_Row_Index (I); declare Value : constant Util.Beans.Objects.Object := List.Get_Row; Label : constant String := Util.Beans.Objects.To_String (Value); begin Render_Item (Label); end; end loop; end if; end if; Writer.Write (']'); end Render_List; overriding procedure Process_Updates (UI : in out UIComplete; Context : in out Faces_Context'Class) is begin if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then declare Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match"); ME : EL.Expressions.Method_Expression; begin if Value /= null then declare VE : constant EL.Expressions.Value_Expression := ASF.Views.Nodes.Get_Value_Expression (Value.all); begin VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all); end; end if; -- Post an event on this component to trigger the rendering of the completion -- list as part of an application/json output. The rendering is made by Broadcast. ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => ME); end; else ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context); end if; -- exception -- when E : others => -- UI.Is_Valid := False; -- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context); -- Log.Info (Utils.Get_Line_Info (UI) -- & ": Exception raised when updating value {0} for component {1}: {2}", -- EL.Objects.To_String (UI.Submitted_Value), -- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E)); end Process_Updates; -- ------------------------------ -- 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 UIComplete; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class) is pragma Unreferenced (Event); Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value); begin Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8"); UI.Render_List (Match, Context); Context.Response_Completed; end Broadcast; end ASF.Components.Widgets.Inputs;
Use the attribute 'autocompleteList' to define the list of autocompletion
Use the attribute 'autocompleteList' to define the list of autocompletion
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f9df6d7e105221269a7b7d1d4d20f9cc093065b9
regtests/el-expressions-tests.adb
regtests/el-expressions-tests.adb
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", " 42"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", " 43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "Joe is#{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); end Test_Parse_Error; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); end Add_Tests; end EL.Expressions.Tests;
----------------------------------------------------------------------- -- EL testsuite - EL Testsuite -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AUnit.Test_Caller; with AUnit.Assertions; with EL.Expressions; with Test_Bean; package body EL.Expressions.Tests is use Test_Bean; use EL.Expressions; use AUnit.Assertions; use AUnit.Test_Fixtures; procedure Check_Error (T : in out Test'Class; Expr : in String); -- Check that evaluating an expression raises an exception procedure Check_Error (T : in out Test'Class; Expr : in String) is E : Expression; begin E := Create_Expression (Context => T.Context, Expr => Expr); pragma Unreferenced (E); Assert (Condition => False, Message => "Evaludation of '" & Expr & "' should raise an exception"); exception when Invalid_Expression => null; end Check_Error; -- Check that evaluating an expression returns the expected result -- (to keep the test simple, results are only checked using strings) procedure Check (T : in out Test; Expr : in String; Expect : in String) is E : constant Expression := Create_Expression (Context => T.Context, Expr => Expr); V : constant Object := E.Get_Value (Context => T.Context); begin Assert (Condition => To_String (V) = Expect, Message => "Evaluate '" & Expr & "' returned '" & To_String (V) & "' when we expect '" & Expect & "'"); declare E2 : constant Expression := E.Reduce_Expression (Context => T.Context); V2 : constant Object := E2.Get_Value (Context => T.Context); begin Assert (To_String (V2) = Expect, "Reduce produced incorrect result: " & To_String (V2)); end; end Check; -- Test evaluation of expression using a bean procedure Test_Bean_Evaluation (T : in out Test) is P : constant Person_Access := Create_Person ("Joe", "Black", 42); begin T.Context.Set_Variable ("user", P); Check (T, "#{empty user}", "FALSE"); Check (T, "#{not empty user}", "TRUE"); Check (T, "#{user.firstName}", "Joe"); Check (T, "#{user.lastName}", "Black"); Check (T, "#{user.age}", " 42"); Check (T, "#{user.date}", To_String (To_Object (P.Date))); Check (T, "#{user.weight}", To_String (To_Object (P.Weight))); P.Age := P.Age + 1; Check (T, "#{user.age}", " 43"); Check (T, "#{user.firstName & ' ' & user.lastName}", "Joe Black"); Check (T, "Joe is#{user.age} year#{user.age > 0 ? 's' : ''} old", "Joe is 43 years old"); end Test_Bean_Evaluation; -- Test evaluation of expression using a bean procedure Test_Parse_Error (T : in out Test) is begin Check_Error (T, "#{1 +}"); Check_Error (T, "#{12(}"); Check_Error (T, "#{foo(1)}"); Check_Error (T, "#{1+2+'abc}"); Check_Error (T, "#{1+""}"); Check_Error (T, "#{12"); Check_Error (T, "${1"); Check_Error (T, "test #{'}"); end Test_Parse_Error; package Caller is new AUnit.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Suite.Add_Test (Caller.Create ("Test EL.Contexts.Set_Variable", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Beans.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Get_Value", Test_Bean_Evaluation'Access)); Suite.Add_Test (Caller.Create ("Test EL.Expressions.Create_Expression (Parse Error)", Test_Parse_Error'Access)); end Add_Tests; end EL.Expressions.Tests;
Add test for empty operator
Add test for empty operator
Ada
apache-2.0
stcarrez/ada-el
0d0b78a9240ea9f3942161bd9335cc29a842c8ae
regtests/util-listeners-tests.adb
regtests/util-listeners-tests.adb
----------------------------------------------------------------------- -- util-listeners-tests -- Unit tests for listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Measures; with Util.Test_Caller; with Util.Listeners.Observers; with Util.Listeners.Lifecycles; package body Util.Listeners.Tests is use Util.Tests; Test_Error : exception; Count : Natural := 0; package String_Observers is new Util.Listeners.Observers (String); package Integer_Observers is new Util.Listeners.Observers (Integer); type String_Listener is new String_Observers.Observer with record Expect : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Update (Listener : in String_Listener; Item : in String); type Integer_Listener is new Integer_Observers.Observer with record Expect : Integer; end record; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer); package Caller is new Util.Test_Caller (Test, "Listeners"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Listeners.Publish", Test_Publish'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Publish_Perf", Test_Publish_Perf'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Lifecycles", Test_Lifecycles'Access); end Add_Tests; overriding procedure Update (Listener : in String_Listener; Item : in String) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; -- ------------------------------ -- Test the listeners and the publish operation. -- ------------------------------ procedure Test_Publish (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased String_Listener; L2 : aliased Integer_Listener; L3 : aliased Integer_Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); Listeners.Append (L3'Unchecked_Access); L1.Expect := Ada.Strings.Unbounded.To_Unbounded_String ("Hello"); String_Observers.Notify (Listeners, "Hello"); Util.Tests.Assert_Equals (T, 1, Count, "Invalid number of calls"); L2.Expect := 3; L3.Expect := 3; Integer_Observers.Notify (Listeners, 3); end Test_Publish; -- ------------------------------ -- Performance test for the listeners. -- ------------------------------ procedure Test_Publish_Perf (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; procedure Test_Basic (Item : in Integer) is begin Util.Tests.Assert_Equals (T, 3, Item); end Test_Basic; begin Listeners.Append (L1'Unchecked_Access); L1.Expect := 3; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Integer_Observers.Notify (Listeners, 3); end loop; Util.Measures.Report (S, "Published 1000 times"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Test_Basic (3); end loop; Util.Measures.Report (S, "Call basic 1000 times"); end; end Test_Publish_Perf; -- ------------------------------ -- Test the lifecycles listener. -- ------------------------------ procedure Test_Lifecycles (T : in out Test) is package TL is new Util.Listeners.Lifecycles (Util.Measures.Stamp); Create_Count : Natural := 0; Update_Count : Natural := 0; Delete_Count : Natural := 0; type Listener is new TL.Listener with null record; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp); -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Create_Count := Create_Count + 1; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Update_Count := Update_Count + 1; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Delete_Count := Delete_Count + 1; end On_Delete; Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; L2 : aliased Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); declare S : Util.Measures.Stamp; begin TL.Notify_Create (Listeners, S); TL.Notify_Update (Listeners, S); TL.Notify_Delete (Listeners, S); Util.Measures.Report (S, "Notify Create, Update, Delete"); end; Util.Tests.Assert_Equals (T, 1, Create_Count, "On_Create not called"); Util.Tests.Assert_Equals (T, 1, Update_Count, "On_Update not called"); Util.Tests.Assert_Equals (T, 1, Delete_Count, "On_Delete not called"); end Test_Lifecycles; end Util.Listeners.Tests;
----------------------------------------------------------------------- -- util-listeners-tests -- Unit tests for listeners -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Measures; with Util.Test_Caller; with Util.Listeners.Observers; with Util.Listeners.Lifecycles; package body Util.Listeners.Tests is use Util.Tests; Test_Error : exception; Count : Natural := 0; package String_Observers is new Util.Listeners.Observers (String); package Integer_Observers is new Util.Listeners.Observers (Integer); type String_Listener is new String_Observers.Observer with record Expect : Ada.Strings.Unbounded.Unbounded_String; end record; overriding procedure Update (Listener : in String_Listener; Item : in String); type Integer_Listener is new Integer_Observers.Observer with record Expect : Integer; end record; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer); package Caller is new Util.Test_Caller (Test, "Listeners"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Listeners.Publish", Test_Publish'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Publish_Perf", Test_Publish_Perf'Access); Caller.Add_Test (Suite, "Test Util.Listeners.Lifecycles", Test_Lifecycles'Access); end Add_Tests; overriding procedure Update (Listener : in String_Listener; Item : in String) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; overriding procedure Update (Listener : in Integer_Listener; Item : in Integer) is use type Ada.Strings.Unbounded.Unbounded_String; begin if Item /= Listener.Expect then raise Test_Error; end if; Count := Count + 1; end Update; -- ------------------------------ -- Test the listeners and the publish operation. -- ------------------------------ procedure Test_Publish (T : in out Test) is Listeners : Util.Listeners.List; L1 : aliased String_Listener; L2 : aliased Integer_Listener; L3 : aliased Integer_Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); Listeners.Append (L3'Unchecked_Access); L1.Expect := Ada.Strings.Unbounded.To_Unbounded_String ("Hello"); String_Observers.Notify (Listeners, "Hello"); Util.Tests.Assert_Equals (T, 1, Count, "Invalid number of calls"); L2.Expect := 3; L3.Expect := 3; Integer_Observers.Notify (Listeners, 3); end Test_Publish; -- ------------------------------ -- Performance test for the listeners. -- ------------------------------ procedure Test_Publish_Perf (T : in out Test) is procedure Test_Basic (Item : in Integer); Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; procedure Test_Basic (Item : in Integer) is begin Util.Tests.Assert_Equals (T, 3, Item); end Test_Basic; begin Listeners.Append (L1'Unchecked_Access); L1.Expect := 3; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Integer_Observers.Notify (Listeners, 3); end loop; Util.Measures.Report (S, "Published 1000 times"); end; declare S : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop Test_Basic (3); end loop; Util.Measures.Report (S, "Call basic 1000 times"); end; end Test_Publish_Perf; -- ------------------------------ -- Test the lifecycles listener. -- ------------------------------ procedure Test_Lifecycles (T : in out Test) is package TL is new Util.Listeners.Lifecycles (Util.Measures.Stamp); Create_Count : Natural := 0; Update_Count : Natural := 0; Delete_Count : Natural := 0; type Listener is new TL.Listener with null record; -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp); -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp); -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation -- of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Create_Count := Create_Count + 1; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Update_Count := Update_Count + 1; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion -- of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Listener; Item : in Util.Measures.Stamp) is pragma Unreferenced (Instance, Item); begin Delete_Count := Delete_Count + 1; end On_Delete; Listeners : Util.Listeners.List; L1 : aliased Integer_Listener; L2 : aliased Listener; begin Listeners.Append (L1'Unchecked_Access); Listeners.Append (L2'Unchecked_Access); declare S : Util.Measures.Stamp; begin TL.Notify_Create (Listeners, S); TL.Notify_Update (Listeners, S); TL.Notify_Delete (Listeners, S); Util.Measures.Report (S, "Notify Create, Update, Delete"); end; Util.Tests.Assert_Equals (T, 1, Create_Count, "On_Create not called"); Util.Tests.Assert_Equals (T, 1, Update_Count, "On_Update not called"); Util.Tests.Assert_Equals (T, 1, Delete_Count, "On_Delete not called"); end Test_Lifecycles; end Util.Listeners.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
266c2d00a6a7a28b9bc638386efdd2bfe677cb55
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- 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 Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- 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 Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- Compare two files on their name and directory. -- ------------------------------ function "<" (Left, Right : in File_Type) return Boolean is use type Ada.Strings.Unbounded.Unbounded_String; begin if Left = NO_FILE then return False; elsif Right = NO_FILE then return True; elsif Left.Dir = Right.Dir then return Left.Name < Right.Name; elsif Left.Dir = NO_DIRECTORY then return True; elsif Right.Dir = NO_DIRECTORY then return False; else return Left.Dir.Path < Right.Dir.Path; end if; end "<"; -- ------------------------------ -- Allocate a File_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return File_Type is use Ada.Strings.Unbounded; Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin return Result; end Allocate; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); else Result.Path := To_Unbounded_String (Name); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Return true if the file is a new file. -- ------------------------------ function Is_New (Element : in File_Type) return Boolean is use type ADO.Identifier; begin return Element.Id = NO_IDENTIFIER; end Is_New; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Return the file size. -- ------------------------------ function Get_Size (Element : in File_Type) return File_Size is begin return Element.Size; end Get_Size; -- ------------------------------ -- Return the file modification date. -- ------------------------------ function Get_Date (Element : in File_Type) return Ada.Calendar.Time is begin return Element.Date; end Get_Date; -- ------------------------------ -- Return the user uid. -- ------------------------------ function Get_User (Element : in File_Type) return Uid_Type is begin return Element.User; end Get_User; -- ------------------------------ -- Return the group gid. -- ------------------------------ function Get_Group (Element : in File_Type) return Gid_Type is begin return Element.Group; end Get_Group; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; -- ------------------------------ -- Execute the Process procedure on each file found in the container. -- ------------------------------ overriding procedure Each_File (Container : in Default_Container; Process : not null access procedure (F : in File_Type)) is Iter : File_Vectors.Cursor := Container.Files.First; begin while File_Vectors.Has_Element (Iter) loop Process (File_Vectors.Element (Iter)); File_Vectors.Next (Iter); end loop; end Each_File; end Babel.Files;
Implement the Get_Group operation
Implement the Get_Group operation
Ada
apache-2.0
stcarrez/babel
5c4d01360d0e88704c0df8e2a8fe4eac8889775c
src/http/aws/util-http-clients-web.adb
src/http/aws/util-http-clients-web.adb
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers.Set; with AWS.Client; with AWS.Messages; package body Util.Http.Clients.Web is Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers); end Do_Get; procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers); end Do_Post; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
----------------------------------------------------------------------- -- util-http-clients-web -- HTTP Clients with AWS implementation -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWS.Headers.Set; with AWS.Client; with AWS.Messages; with Util.Log.Loggers; package body Util.Http.Clients.Web is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web"); Manager : aliased AWS_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; function To_Status (Code : in AWS.Messages.Status_Code) return Natural; function To_Status (Code : in AWS.Messages.Status_Code) return Natural is use AWS.Messages; begin case Code is when S100 => return 100; when S101 => return 101; when S102 => return 102; when S200 => return 200; when S201 => return 201; when S203 => return 203; when S204 => return 204; when S205 => return 205; when S206 => return 206; when S207 => return 207; when S300 => return 300; when S301 => return 301; when S302 => return 302; when S303 => return 303; when S304 => return 304; when S305 => return 305; when S307 => return 307; when S400 => return 400; when S401 => return 401; when S402 => return 402; when S403 => return 403; when S404 => return 404; when S405 => return 405; when S406 => return 406; when S407 => return 407; when S408 => return 408; when S409 => return 409; when S410 => return 410; when S411 => return 411; when S412 => return 412; when S413 => return 413; when S414 => return 414; when S415 => return 415; when S416 => return 416; when S417 => return 417; when S422 => return 422; when S423 => return 423; when S424 => return 424; when S500 => return 500; when S501 => return 501; when S502 => return 502; when S503 => return 503; when S504 => return 504; when S505 => return 505; when S507 => return 507; when others => return 500; end case; end To_Status; procedure Create (Manager : in AWS_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new AWS_Http_Request; end Create; procedure Do_Get (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Get {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers); end Do_Get; procedure Do_Post (Manager : in AWS_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Manager); Req : constant AWS_Http_Request_Access := AWS_Http_Request'Class (Http.Delegate.all)'Access; Rep : constant AWS_Http_Response_Access := new AWS_Http_Response; begin Log.Info ("Post {0}", URI); Reply.Delegate := Rep.all'Access; Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers); end Do_Post; -- ------------------------------ -- Returns a boolean indicating whether the named request header has already -- been set. -- ------------------------------ function Contains_Header (Http : in AWS_Http_Request; Name : in String) return Boolean is begin raise Program_Error with "Contains_Header is not implemented"; return False; end Contains_Header; -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. overriding function Get_Header (Request : in AWS_Http_Request; Name : in String) return String is begin return ""; end Get_Header; -- ------------------------------ -- Sets a request header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Http : in out AWS_Http_Request; Name : in String; Value : in String) is begin AWS.Headers.Set.Add (Http.Headers, Name, Value); end Add_Header; -- Iterate over the request headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Request : in AWS_Http_Request; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Reply : in AWS_Http_Response; Name : in String) return Boolean is begin return AWS.Response.Header (Reply.Data, Name) /= ""; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Reply : in AWS_Http_Response; Name : in String) return String is begin return AWS.Response.Header (Reply.Data, Name); end Get_Header; -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. overriding procedure Set_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Set_Header; -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. overriding procedure Add_Header (Reply : in out AWS_Http_Response; Name : in String; Value : in String) is begin null; end Add_Header; -- Iterate over the response headers and executes the <b>Process</b> procedure. overriding procedure Iterate_Headers (Reply : in AWS_Http_Response; Process : not null access procedure (Name : in String; Value : in String)) is begin null; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ function Get_Body (Reply : in AWS_Http_Response) return String is begin return AWS.Response.Message_Body (Reply.Data); end Get_Body; -- Get the response status code. overriding function Get_Status (Reply : in AWS_Http_Response) return Natural is begin return To_Status (AWS.Response.Status_Code (Reply.Data)); end Get_Status; end Util.Http.Clients.Web;
Add some log to help solving web issues
Add some log to help solving web issues
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b7e070ea64169cd5e4c50f690111b8d7e5b57fe4
mat/src/mat-consoles-text.adb
mat/src/mat-consoles-text.adb
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- 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) is use type Ada.Text_IO.Count; Pos : Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); Size : constant Natural := Console.Sizes (Field); Start : Natural := Value'First; Last : Natural := Value'Last; Pad : Natural := 0; Fill : Natural := 0; begin case Justify is when J_LEFT => if Value'Length < Size then Fill := Size - Value'Length; else Start := Last - Size + 1; end if; when J_RIGHT => if Value'Length < Size then Pad := Size - Value'Length - 1; else Start := Last - Size + 1; end if; when J_CENTER => if Value'Length < Size then Pad := (Size - Value'Length) / 2; Fill := Size - Value'Length - Pad; else Start := Last - Size + 1; end if; when J_RIGHT_NO_FILL => if Value'Length >= Size then Start := Last - Size + 1; end if; end case; if Pad > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad)); elsif Pos > 1 then Ada.Text_IO.Set_Col (Pos); end if; Ada.Text_IO.Put (Value (Start .. Last)); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Report an error message. -- ------------------------------ overriding procedure Error (Console : in out Console_Type; Message : in String) is pragma Unreferenced (Console); begin Ada.Text_IO.Put_Line (Message); end Error; -- ------------------------------ -- Report a notice message. -- ------------------------------ overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is pragma Unreferenced (Console, Kind); begin Ada.Text_IO.Put_Line (Message); end Notice; -- ------------------------------ -- 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) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); Size : constant Natural := Console.Sizes (Field); Start : Natural := Value'First; Last : constant Natural := Value'Last; Pad : Natural := 0; begin case Justify is when J_LEFT => if Value'Length > Size then Start := Last - Size + 1; end if; when J_RIGHT => if Value'Length < Size then Pad := Size - Value'Length - 1; else Start := Last - Size + 1; end if; when J_CENTER => if Value'Length < Size then Pad := (Size - Value'Length) / 2; else Start := Last - Size + 1; end if; when J_RIGHT_NO_FILL => if Value'Length >= Size then Start := Last - Size + 1; end if; end case; if Pad > 0 then Ada.Text_IO.Set_Col (Pos + Ada.Text_IO.Count (Pad)); elsif Pos > 1 then Ada.Text_IO.Set_Col (Pos); end if; Ada.Text_IO.Put (Value (Start .. Last)); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is use type Ada.Text_IO.Count; Pos : constant Ada.Text_IO.Count := Ada.Text_IO.Count (Console.Cols (Field)); begin if Pos > 1 then Ada.Text_IO.Set_Col (Pos); end if; Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is pragma Unreferenced (Console); begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9b002529dcce84625a78e7fa6b24dac323fe24ef
src/asf-components-html-forms.ads
src/asf-components-html-forms.ads
----------------------------------------------------------------------- -- html.forms -- ASF HTML Form Components -- 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.Holders; with ASF.Components.Html.Text; with ASF.Validators; with ASF.Events.Faces; with EL.Objects; with EL.Expressions; package ASF.Components.Html.Forms is -- A UIComponent can have several validators. To keep the implementation light and -- simple, a fixed array is used. Most components will have one or two validators. -- Define the number of validators per component (UIInput). MAX_VALIDATORS_PER_COMPONENT : constant Positive := 5; -- Message displayed when the submitted value is required but is empty. REQUIRED_MESSAGE_ID : constant String := "asf.faces.component.UIInput.REQUIRED"; -- ------------------------------ -- Form Component -- ------------------------------ type UIForm is new UIHtmlComponent with private; type UIForm_Access is access all UIForm'Class; -- Check whether the form is submitted. function Is_Submitted (UI : in UIForm) return Boolean; -- Called during the <b>Apply Request</b> phase to indicate that this -- form is submitted. procedure Set_Submitted (UI : in out UIForm); -- Get the action URL to set on the HTML form function Get_Action (UI : in UIForm; Context : in Faces_Context'Class) return String; overriding procedure Encode_Begin (UI : in UIForm; Context : in out Faces_Context'Class); overriding procedure Encode_End (UI : in UIForm; Context : in out Faces_Context'Class); overriding procedure Decode (UI : in out UIForm; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIForm; Context : in out Faces_Context'Class); -- ------------------------------ -- Input Component -- ------------------------------ type UIInput is new Text.UIOutput and Holders.Editable_Value_Holder with private; type UIInput_Access is access all UIInput'Class; -- Check if this component has the required attribute set. function Is_Required (UI : in UIInput; Context : in Faces_Context'Class) return Boolean; -- Find the form component which contains the input component. -- Returns null if the input is not within a form component. function Get_Form (UI : in UIInput) return UIForm_Access; -- Get the value of the component. If the component has a submitted value, returns it. -- If the component has a local value which is not null, returns it. -- Otherwise, if we have a Value_Expression evaluate and returns the value. overriding function Get_Value (UI : in UIInput) return EL.Objects.Object; -- Set the input component as a password field. procedure Set_Secret (UI : in out UIInput; Value : in Boolean); -- Render the input element. procedure Render_Input (UI : in UIInput; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); overriding procedure Encode_Begin (UI : in UIInput; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIInput; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> procedure Process_Validators (UI : in out UIInput; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIInput; Context : in out Faces_Context'Class); -- Validate the submitted value. -- <ul> -- <li>Retreive the submitted value -- <li>If the value is null, exit without further processing. -- <li>Validate the value by calling <b>Validate_Value</b> -- </ul> procedure Validate (UI : in out UIInput; Context : in out Faces_Context'Class); -- Set the <b>valid</b> property: -- <ul> -- <li>If the <b>required</b> property is true, ensure the -- value is not empty -- <li>Call the <b>Validate</b> procedure on each validator -- registered on this component. -- <li>Set the <b>valid</b> property if all validator passed. -- </ul> procedure Validate_Value (UI : in out UIInput; Value : in EL.Objects.Object; Context : in out Faces_Context'Class); -- Add the validator to be used on the component. The ASF implementation limits -- to 5 the number of validators that can be set on a component (See UIInput). -- The validator instance will be freed when the editable value holder is deleted -- unless <b>Shared</b> is true. overriding procedure Add_Validator (UI : in out UIInput; Validator : in ASF.Validators.Validator_Access; Shared : in Boolean := False); -- Delete the UI input instance. overriding procedure Finalize (UI : in out UIInput); -- ------------------------------ -- InputTextarea Component -- ------------------------------ type UIInputTextarea is new UIInput with private; type UIInputTextarea_Access is access all UIInputTextarea'Class; -- Render the textarea element. overriding procedure Render_Input (UI : in UIInputTextarea; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- ------------------------------ -- Input_Hidden Component -- ------------------------------ type UIInput_Hidden is new UIInput with private; type UIInput_Hidden_Access is access all UIInput_Hidden'Class; -- Render the inputHidden element. overriding procedure Render_Input (UI : in UIInput_Hidden; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- ------------------------------ -- InputFile Component -- ------------------------------ type UIInput_File is new UIInput with private; type UIInput_File_Access is access all UIInput_File'Class; -- Render the input file element. overriding procedure Render_Input (UI : in UIInput_File; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- Validate the submitted file. -- <ul> -- <li>Retreive the submitted value -- <li>If the value is null, exit without further processing. -- <li>Validate the value by calling <b>Validate_Value</b> -- </ul> overriding procedure Validate (UI : in out UIInput_File; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIInput_File; Context : in out Faces_Context'Class); -- ------------------------------ -- Button Component -- ------------------------------ type UICommand is new UIHtmlComponent with private; overriding procedure Encode_Begin (UI : in UICommand; Context : in out Faces_Context'Class); -- Get the value to write on the output. function Get_Value (UI : in UICommand) return EL.Objects.Object; -- Set the value to write on the output. procedure Set_Value (UI : in out UICommand; Value : in EL.Objects.Object); -- Get the action method expression to invoke if the command is pressed. function Get_Action_Expression (UI : in UICommand; Context : in Faces_Context'Class) return EL.Expressions.Method_Expression; overriding procedure Process_Decodes (UI : in out UICommand; Context : in out 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 UICommand; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class); private type Validator is record Validator : ASF.Validators.Validator_Access := null; Shared : Boolean := False; end record; type Validator_Array is array (1 .. MAX_VALIDATORS_PER_COMPONENT) of Validator; type UIInput is new Text.UIOutput and Holders.Editable_Value_Holder with record Submitted_Value : EL.Objects.Object; Is_Valid : Boolean := False; Is_Secret : Boolean := False; Validators : Validator_Array; end record; type UIInputTextarea is new UIInput with record Rows : Natural; Cols : Natural; end record; type UIInput_Hidden is new UIInput with null record; type UIInput_File is new UIInput with null record; type UICommand is new UIHtmlComponent with record Value : EL.Objects.Object; end record; type UIForm is new UIHtmlComponent with record Is_Submitted : Boolean := False; end record; end ASF.Components.Html.Forms;
----------------------------------------------------------------------- -- html.forms -- ASF HTML Form Components -- Copyright (C) 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 ASF.Components.Holders; with ASF.Components.Html.Text; with ASF.Validators; with ASF.Events.Faces; with EL.Objects; with EL.Expressions; package ASF.Components.Html.Forms is -- A UIComponent can have several validators. To keep the implementation light and -- simple, a fixed array is used. Most components will have one or two validators. -- Define the number of validators per component (UIInput). MAX_VALIDATORS_PER_COMPONENT : constant Positive := 5; -- Message displayed when the submitted value is required but is empty. REQUIRED_MESSAGE_ID : constant String := "asf.faces.component.UIInput.REQUIRED"; -- ------------------------------ -- Form Component -- ------------------------------ type UIForm is new UIHtmlComponent with private; type UIForm_Access is access all UIForm'Class; -- Check whether the form is submitted. function Is_Submitted (UI : in UIForm) return Boolean; -- Called during the <b>Apply Request</b> phase to indicate that this -- form is submitted. procedure Set_Submitted (UI : in out UIForm); -- Get the action URL to set on the HTML form function Get_Action (UI : in UIForm; Context : in Faces_Context'Class) return String; overriding procedure Encode_Begin (UI : in UIForm; Context : in out Faces_Context'Class); overriding procedure Encode_End (UI : in UIForm; Context : in out Faces_Context'Class); overriding procedure Decode (UI : in out UIForm; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIForm; Context : in out Faces_Context'Class); -- ------------------------------ -- Input Component -- ------------------------------ type UIInput is new Text.UIOutput and Holders.Editable_Value_Holder with private; type UIInput_Access is access all UIInput'Class; -- Check if this component has the required attribute set. function Is_Required (UI : in UIInput; Context : in Faces_Context'Class) return Boolean; -- Find the form component which contains the input component. -- Returns null if the input is not within a form component. function Get_Form (UI : in UIInput) return UIForm_Access; -- Get the value of the component. If the component has a submitted value, returns it. -- If the component has a local value which is not null, returns it. -- Otherwise, if we have a Value_Expression evaluate and returns the value. overriding function Get_Value (UI : in UIInput) return EL.Objects.Object; -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. function Get_Parameter (UI : in UIInput; Context : in Faces_Context'Class) return String; -- Set the input component as a password field. procedure Set_Secret (UI : in out UIInput; Value : in Boolean); -- Render the input element. procedure Render_Input (UI : in UIInput; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); overriding procedure Encode_Begin (UI : in UIInput; Context : in out Faces_Context'Class); overriding procedure Process_Decodes (UI : in out UIInput; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> procedure Process_Validators (UI : in out UIInput; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIInput; Context : in out Faces_Context'Class); -- Validate the submitted value. -- <ul> -- <li>Retreive the submitted value -- <li>If the value is null, exit without further processing. -- <li>Validate the value by calling <b>Validate_Value</b> -- </ul> procedure Validate (UI : in out UIInput; Context : in out Faces_Context'Class); -- Set the <b>valid</b> property: -- <ul> -- <li>If the <b>required</b> property is true, ensure the -- value is not empty -- <li>Call the <b>Validate</b> procedure on each validator -- registered on this component. -- <li>Set the <b>valid</b> property if all validator passed. -- </ul> procedure Validate_Value (UI : in out UIInput; Value : in EL.Objects.Object; Context : in out Faces_Context'Class); -- Add the validator to be used on the component. The ASF implementation limits -- to 5 the number of validators that can be set on a component (See UIInput). -- The validator instance will be freed when the editable value holder is deleted -- unless <b>Shared</b> is true. overriding procedure Add_Validator (UI : in out UIInput; Validator : in ASF.Validators.Validator_Access; Shared : in Boolean := False); -- Delete the UI input instance. overriding procedure Finalize (UI : in out UIInput); -- ------------------------------ -- InputTextarea Component -- ------------------------------ type UIInputTextarea is new UIInput with private; type UIInputTextarea_Access is access all UIInputTextarea'Class; -- Render the textarea element. overriding procedure Render_Input (UI : in UIInputTextarea; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- ------------------------------ -- Input_Hidden Component -- ------------------------------ type UIInput_Hidden is new UIInput with private; type UIInput_Hidden_Access is access all UIInput_Hidden'Class; -- Render the inputHidden element. overriding procedure Render_Input (UI : in UIInput_Hidden; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- ------------------------------ -- InputFile Component -- ------------------------------ type UIInput_File is new UIInput with private; type UIInput_File_Access is access all UIInput_File'Class; -- Render the input file element. overriding procedure Render_Input (UI : in UIInput_File; Context : in out Faces_Context'Class; Write_Id : in Boolean := True); -- Validate the submitted file. -- <ul> -- <li>Retreive the submitted value -- <li>If the value is null, exit without further processing. -- <li>Validate the value by calling <b>Validate_Value</b> -- </ul> overriding procedure Validate (UI : in out UIInput_File; Context : in out Faces_Context'Class); overriding procedure Process_Updates (UI : in out UIInput_File; Context : in out Faces_Context'Class); -- ------------------------------ -- Button Component -- ------------------------------ type UICommand is new UIHtmlComponent with private; overriding procedure Encode_Begin (UI : in UICommand; Context : in out Faces_Context'Class); -- Get the value to write on the output. function Get_Value (UI : in UICommand) return EL.Objects.Object; -- Set the value to write on the output. procedure Set_Value (UI : in out UICommand; Value : in EL.Objects.Object); -- Get the action method expression to invoke if the command is pressed. function Get_Action_Expression (UI : in UICommand; Context : in Faces_Context'Class) return EL.Expressions.Method_Expression; overriding procedure Process_Decodes (UI : in out UICommand; Context : in out 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 UICommand; Event : not null access ASF.Events.Faces.Faces_Event'Class; Context : in out Faces_Context'Class); private type Validator is record Validator : ASF.Validators.Validator_Access := null; Shared : Boolean := False; end record; type Validator_Array is array (1 .. MAX_VALIDATORS_PER_COMPONENT) of Validator; type UIInput is new Text.UIOutput and Holders.Editable_Value_Holder with record Submitted_Value : EL.Objects.Object; Is_Valid : Boolean := False; Is_Secret : Boolean := False; Validators : Validator_Array; end record; type UIInputTextarea is new UIInput with record Rows : Natural; Cols : Natural; end record; type UIInput_Hidden is new UIInput with null record; type UIInput_File is new UIInput with null record; type UICommand is new UIHtmlComponent with record Value : EL.Objects.Object; end record; type UIForm is new UIHtmlComponent with record Is_Submitted : Boolean := False; end record; end ASF.Components.Html.Forms;
Declare the Get_Parameter function for UIInput tagged record
Declare the Get_Parameter function for UIInput tagged record
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8b598fdc7534734f5406b02be10a9da750b834c9
regtests/ado-schemas-tests.adb
regtests/ado-schemas-tests.adb
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Sessions; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "ID", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "NAME", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Connection.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 15, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 9, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; end ADO.Schemas.Tests;
----------------------------------------------------------------------- -- schemas Tests -- Test loading of database schema -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Sessions; with ADO.Schemas.Entities; with Regtests; with Regtests.Simple.Model; package body ADO.Schemas.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "ADO.Schemas"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type", Test_Find_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)", Test_Find_Entity_Type_Error'Access); Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema", Test_Load_Schema'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table", Test_Table_Iterator'Access); Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)", Test_Empty_Schema'Access); end Add_Tests; -- ------------------------------ -- Test reading the entity cache and the Find_Entity_Type operation -- ------------------------------ procedure Test_Find_Entity_Type (T : in out Test) is S : ADO.Sessions.Session := Regtests.Get_Database; C : ADO.Schemas.Entities.Entity_Cache; begin ADO.Schemas.Entities.Initialize (Cache => C, Session => S); declare -- T1 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.USER_TABLE'Access); -- T2 : constant ADO.Model.Entity_Type_Ref -- := Entities.Find_Entity_Type (Cache => C, -- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access); T4 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.ALLOCATE_TABLE); T5 : constant ADO.Entity_Type := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); begin -- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value"); -- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value"); T.Assert (T4 /= T5, "Two distinct tables have different entity types"); T.Assert (T4 > 0, "T1.Id must be positive"); T.Assert (T5 > 0, "T2.Id must be positive"); -- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids"); -- -- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4), -- "Invalid entity type for allocate_table"); -- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5), -- "Invalid entity type for user_table"); end; end Test_Find_Entity_Type; -- ------------------------------ -- Test calling Find_Entity_Type with an invalid table. -- ------------------------------ procedure Test_Find_Entity_Type_Error (T : in out Test) is C : ADO.Schemas.Entities.Entity_Cache; begin declare R : ADO.Entity_Type; pragma Unreferenced (R); begin R := Entities.Find_Entity_Type (Cache => C, Table => Regtests.Simple.Model.USER_TABLE); T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception"); exception when ADO.Schemas.Entities.No_Entity_Type => null; end; end Test_Find_Entity_Type_Error; -- ------------------------------ -- Test the Load_Schema operation and check the result schema. -- ------------------------------ procedure Test_Load_Schema (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; begin S.Load_Schema (Schema); Table := ADO.Schemas.Find_Table (Schema, "allocate"); T.Assert (Table /= null, "Table schema for test_allocate not found"); Assert_Equals (T, "allocate", Get_Name (Table)); declare C : Column_Cursor := Get_Columns (Table); Nb_Columns : Integer := 0; begin while Has_Element (C) loop Nb_Columns := Nb_Columns + 1; Next (C); end loop; Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns"); end; declare C : constant Column_Definition := Find_Column (Table, "ID"); begin T.Assert (C /= null, "Cannot find column 'id' in table schema"); Assert_Equals (T, "ID", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "NAME"); begin T.Assert (C /= null, "Cannot find column 'NAME' in table schema"); Assert_Equals (T, "NAME", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type"); T.Assert (Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "version"); begin T.Assert (C /= null, "Cannot find column 'version' in table schema"); Assert_Equals (T, "version", Get_Name (C), "Invalid column name"); T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type"); T.Assert (not Is_Null (C), "Column is null"); end; declare C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist"); begin T.Assert (C = null, "Find_Column must return null for an unknown column"); end; end Test_Load_Schema; -- ------------------------------ -- Test the Table_Cursor operations and check the result schema. -- ------------------------------ procedure Test_Table_Iterator (T : in out Test) is S : constant ADO.Sessions.Session := Regtests.Get_Database; Schema : Schema_Definition; Table : Table_Definition; Driver : constant String := S.Get_Connection.Get_Driver.Get_Driver_Name; begin S.Load_Schema (Schema); declare Iter : Table_Cursor := Schema.Get_Tables; Count : Natural := 0; begin T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator"); while Has_Element (Iter) loop Table := Element (Iter); T.Assert (Table /= null, "Element function must not return null"); declare Col_Iter : Column_Cursor := Get_Columns (Table); begin -- T.Assert (Has_Element (Col_Iter), "Table has a column"); while Has_Element (Col_Iter) loop T.Assert (Element (Col_Iter) /= null, "Element function must not return null"); Next (Col_Iter); end loop; end; Count := Count + 1; Next (Iter); end loop; if Driver = "sqlite" then Util.Tests.Assert_Equals (T, 15, Count, "Invalid number of tables found in the schema"); elsif Driver = "mysql" then Util.Tests.Assert_Equals (T, 8, Count, "Invalid number of tables found in the schema"); end if; end; end Test_Table_Iterator; -- ------------------------------ -- Test the Table_Cursor operations on an empty schema. -- ------------------------------ procedure Test_Empty_Schema (T : in out Test) is Schema : Schema_Definition; Iter : constant Table_Cursor := Schema.Get_Tables; begin T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator"); T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null"); end Test_Empty_Schema; end ADO.Schemas.Tests;
Fix the schema unit test
Fix the schema unit test
Ada
apache-2.0
stcarrez/ada-ado
4cf0c7ccf92b60dd389f7ff55bc76a5ba1ed13cd
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with ASF.Tests; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use type AWA.Users.Principals.Principal_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users"); MAX_USERS : constant Positive := 10; Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- ------------------------------ -- Simulate a user login in the given service context. -- ------------------------------ procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); -- Keep track of the Principal instance so that Tear_Down will release it. -- Most tests will call Login but don't call Logout because there is no real purpose -- for the test in doing that and it allows to keep the unit test simple. This creates -- memory leak because the Principal instance is not freed. for I in Logged_Users'Range loop if Logged_Users (I) = null then Logged_Users (I) := Principal; exit; end if; end loop; end Login; -- ------------------------------ -- Simulate a user login on the request. Upon successful login, a session that is -- authentified is associated with the request object. -- ------------------------------ procedure Login (Email : in String; Request : in out ASF.Requests.Mockup.Request) is User : Test_User; Reply : ASF.Responses.Mockup.Response; begin Create_User (User, Email); ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); end Login; -- ------------------------------ -- Setup the context and security context to simulate an anonymous user. -- ------------------------------ procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Context.Set_Context (App, null); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => null); end Anonymous; overriding procedure Finalize (Principal : in out Test_User) is begin Free (Principal.Principal); end Finalize; -- ------------------------------ -- Cleanup and release the Principal that have been allocated from the Login session -- but not released because the Logout is not called from the unit test. -- ------------------------------ procedure Tear_Down is begin for I in Logged_Users'Range loop if Logged_Users (I) /= null then Free (Logged_Users (I)); end if; end loop; end Tear_Down; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with ASF.Principals; with ASF.Tests; with ASF.Responses.Mockup; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use type AWA.Users.Principals.Principal_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Tests.Helpers.Users"); MAX_USERS : constant Positive := 10; Logged_Users : array (1 .. MAX_USERS) of AWA.Users.Principals.Principal_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join awa_email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Signup_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.SIGNUP_KEY); Password_Kind : constant Integer := AWA.Users.Models.Key_Type'Pos (AWA.Users.Models.RESET_PASSWORD_KEY); begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join awa_email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ? AND o.kind = ?"); Query.Bind_Param (1, Email); Query.Bind_Param (2, Signup_Kind); Key.Find (DB, Query, Found); if not Found then Query.Bind_Param (2, Password_Kind); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- ------------------------------ -- Simulate a user login in the given service context. -- ------------------------------ procedure Login (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); -- Keep track of the Principal instance so that Tear_Down will release it. -- Most tests will call Login but don't call Logout because there is no real purpose -- for the test in doing that and it allows to keep the unit test simple. This creates -- memory leak because the Principal instance is not freed. for I in Logged_Users'Range loop if Logged_Users (I) = null then Logged_Users (I) := Principal; exit; end if; end loop; end Login; -- ------------------------------ -- Simulate a user login on the request. Upon successful login, a session that is -- authentified is associated with the request object. -- ------------------------------ procedure Login (Email : in String; Request : in out ASF.Requests.Mockup.Request) is User : Test_User; Reply : ASF.Responses.Mockup.Response; begin Create_User (User, Email); ASF.Tests.Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login", "1"); Request.Set_Parameter ("login-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); end Login; -- ------------------------------ -- Setup the context and security context to simulate an anonymous user. -- ------------------------------ procedure Anonymous (Context : in out AWA.Services.Contexts.Service_Context'Class; Sec_Context : in out Security.Contexts.Security_Context) is App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Context.Set_Context (App, null); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => null); end Anonymous; -- ------------------------------ -- Simulate the recovery password process for the given user. -- ------------------------------ procedure Recover_Password (Email : in String) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password", "1"); Request.Set_Parameter ("lost-password-button", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid redirect after lost password"); end if; -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); if not Key.Is_Null then Log.Error ("There is no access key associated with the user"); end if; -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("reset-password", "1"); ASF.Tests.Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-2.html"); if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then Log.Error ("Invalid response"); end if; -- Check that the user is logged and we have a user principal now. if Request.Get_User_Principal = null then Log.Error ("A user principal should be defined"); end if; end; end Recover_Password; overriding procedure Finalize (Principal : in out Test_User) is begin Free (Principal.Principal); end Finalize; -- ------------------------------ -- Cleanup and release the Principal that have been allocated from the Login session -- but not released because the Logout is not called from the unit test. -- ------------------------------ procedure Tear_Down is begin for I in Logged_Users'Range loop if Logged_Users (I) /= null then Free (Logged_Users (I)); end if; end loop; end Tear_Down; end AWA.Tests.Helpers.Users;
Implement the Recover_Password procedure to simulate a password recovery and reset the password for the user to the test password 'admin' Update Find_Access_Key to find the access key according to a SIGNUP_KEY or a RESET_PASSWORD_KEY type
Implement the Recover_Password procedure to simulate a password recovery and reset the password for the user to the test password 'admin' Update Find_Access_Key to find the access key according to a SIGNUP_KEY or a RESET_PASSWORD_KEY type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ee7e7fd1145a7b16c0a7b43c7670c23fb57c2612
samples/variables.adb
samples/variables.adb
----------------------------------------------------------------------- -- el -- Evaluate an EL expression -- Copyright (C) 2009, 2010 Free Software Foundation, Inc. -- Written by Stephane Carrez ([email protected]) -- -- This file is part of ASF. -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License as -- published by the Free Software Foundation; either version 2, -- or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; see the file COPYING. If not, write to -- the Free Software Foundation, 59 Temple Place - Suite 330, -- Boston, MA 02111-1307, USA. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with EL.Beans; with Ada.Text_IO; with Bean; procedure Variables is use Bean; Joe : Person_Access := Create_Person ("Joe", "Smith", 12); Bill : Person_Access := Create_Person ("Bill", "Johnson", 42); Ctx : EL.Contexts.Default.Default_Context; E : EL.Expressions.Expression; Result : EL.Objects.Object; begin E := EL.Expressions.Create_Expression ("#{user.firstName} #{user.lastName}", Ctx); -- Bind the context to 'Joe' and evaluate Ctx.Set_Variable ("user", Joe); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("Joe's name is " & EL.Objects.To_String (Result)); -- Bind the context to 'Bill' and evaluate Ctx.Set_Variable ("user", Bill); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("Bill's name is " & EL.Objects.To_String (Result)); Free (Joe); Free (Bill); end Variables;
----------------------------------------------------------------------- -- el -- Evaluate an EL expression -- Copyright (C) 2009, 2010 Free Software Foundation, Inc. -- Written by Stephane Carrez ([email protected]) -- -- This file is part of ASF. -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License as -- published by the Free Software Foundation; either version 2, -- or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; see the file COPYING. If not, write to -- the Free Software Foundation, 59 Temple Place - Suite 330, -- Boston, MA 02111-1307, USA. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with Ada.Text_IO; with Bean; procedure Variables is use Bean; Joe : Person_Access := Create_Person ("Joe", "Smith", 12); Bill : Person_Access := Create_Person ("Bill", "Johnson", 42); Ctx : EL.Contexts.Default.Default_Context; E : EL.Expressions.Expression; VE : EL.Expressions.Value_Expression; Result : EL.Objects.Object; begin E := EL.Expressions.Create_Expression ("#{user.firstName} #{user.lastName}", Ctx); -- Bind the context to 'Joe' and evaluate Ctx.Set_Variable ("user", Joe); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result)); -- Bind the context to 'Bill' and evaluate Ctx.Set_Variable ("user", Bill); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result)); -- Create a value expression to change the user firstName property. VE := EL.Expressions.Create_Expression ("#{user.firstName}", Ctx); -- Change the user first name by setting the value expression. VE.Set_Value (Context => Ctx, Value => EL.Objects.To_Object (String '("Harold"))); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result)); Free (Joe); Free (Bill); end Variables;
Add an example of Value_Expression and call to Set_Value
Add an example of Value_Expression and call to Set_Value
Ada
apache-2.0
stcarrez/ada-el
69efcb859896e91d312d8b07e551511816c72cf6
regtests/asf-requests-tests.ads
regtests/asf-requests-tests.ads
----------------------------------------------------------------------- -- asf-requests-tests - Unit tests for requests -- 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.Tests; package ASF.Requests.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Split_Header procedure. procedure Test_Split_Header (T : in out Test); -- Test the Accept_Locales procedure. procedure Test_Accept_Locales (T : in out Test); end ASF.Requests.Tests;
----------------------------------------------------------------------- -- asf-requests-tests - Unit tests for requests -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Requests.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Split_Header procedure. procedure Test_Split_Header (T : in out Test); -- Test the Accept_Locales procedure. procedure Test_Accept_Locales (T : in out Test); -- Test the Set_Attribute procedure. procedure Test_Set_Attribute (T : in out Test); end ASF.Requests.Tests;
Declare the Test_Set_Attribute procedure to check the Set/Get/Remove attribute
Declare the Test_Set_Attribute procedure to check the Set/Get/Remove attribute
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
0ad2b8da66da9d575d81c90e0e49b397d59f799e
src/sqlite/ado-schemas-sqlite.adb
src/sqlite/ado-schemas-sqlite.adb
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- 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 ADO.Statements; with ADO.Statements.Create; with Ada.Strings.Fixed; with Util.Strings.Transforms; package body ADO.Schemas.Sqlite is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int" or Value = "integer" then return T_INTEGER; elsif Value = "bigint" then return T_LONG_INTEGER; elsif Value = "tinyint" then return T_TINYINT; elsif Value = "smallint" then return T_SMALLINT; elsif Value = "blob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "real" or Name = "float" or Name = "double" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("pragma table_info('" & Name & "')")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; begin Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (1); Col.Collation := Stmt.Get_Unbounded_String (2); Col.Default := Stmt.Get_Unbounded_String (5); if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (2); Col.Col_Type := String_To_Type (Util.Strings.Transforms.To_Lower_Case (To_String (Value))); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "0"; Value := Stmt.Get_Unbounded_String (5); Col.Is_Primary := Value = "1"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("SELECT NAME FROM sqlite_master")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop Table := new ADO.Schemas.Table; Table.Name := Stmt.Get_Unbounded_String (0); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Sqlite;
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- 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 ADO.Statements; with ADO.Statements.Create; with Ada.Strings.Fixed; with Util.Strings.Transforms; package body ADO.Schemas.Sqlite is use ADO.Statements; procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition); function String_To_Type (Value : in String) return Column_Type; function String_To_Length (Value : in String) return Natural; function String_To_Type (Value : in String) return Column_Type is Pos : Natural; begin if Value = "date" then return T_DATE; elsif Value = "datetime" then return T_DATE_TIME; elsif Value = "int" or Value = "integer" then return T_INTEGER; elsif Value = "bigint" then return T_LONG_INTEGER; elsif Value = "tinyint" then return T_TINYINT; elsif Value = "smallint" then return T_SMALLINT; elsif Value = "blob" then return T_BLOB; end if; Pos := Ada.Strings.Fixed.Index (Value, "("); if Pos > 0 then declare Name : constant String := Value (Value'First .. Pos - 1); begin if Name = "varchar" then return T_VARCHAR; elsif Name = "real" or Name = "float" or Name = "double" then return T_FLOAT; elsif Name = "int" then return T_INTEGER; elsif Name = "bigint" then return T_LONG_INTEGER; else return T_UNKNOWN; end if; end; end if; return T_UNKNOWN; end String_To_Type; function String_To_Length (Value : in String) return Natural is First : Natural; Last : Natural; begin First := Ada.Strings.Fixed.Index (Value, "("); if First < 0 then return 0; end if; Last := Ada.Strings.Fixed.Index (Value , ")"); if Last < First then return 0; end if; return Natural'Value (Value (First + 1 .. Last - 1)); exception when Constraint_Error => return 0; end String_To_Length; -- ------------------------------ -- Load the table definition -- ------------------------------ procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Table : in Table_Definition) is Name : constant String := Get_Name (Table); Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("pragma table_info('" & Name & "')")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; begin Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (1); Col.Collation := Stmt.Get_Unbounded_String (2); Col.Default := Stmt.Get_Unbounded_String (5); if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (2); declare Type_Name : constant String := Util.Strings.Transforms.To_Lower_Case (To_String (Value)); begin Col.Col_Type := String_To_Type (Type_Name); Col.Size := String_To_Length (Type_Name); end; Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "0"; Value := Stmt.Get_Unbounded_String (5); Col.Is_Primary := Value = "1"; Last := Col; Stmt.Next; end loop; end Load_Table_Schema; -- ------------------------------ -- Load the database schema -- ------------------------------ procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class; Schema : out Schema_Definition) is Stmt : Query_Statement := Create.Create_Statement (C.Create_Statement ("SELECT NAME FROM sqlite_master")); Table : Table_Definition; Last : Table_Definition := null; begin Schema.Schema := new ADO.Schemas.Schema; Stmt.Execute; while Stmt.Has_Elements loop Table := new ADO.Schemas.Table; Table.Name := Stmt.Get_Unbounded_String (0); if Last /= null then Last.Next_Table := Table; else Schema.Schema.First_Table := Table; end if; Load_Table_Schema (C, Table); Last := Table; Stmt.Next; end loop; end Load_Schema; end ADO.Schemas.Sqlite;
Declare and implement String_To_Length and use it to get the column size
Declare and implement String_To_Length and use it to get the column size
Ada
apache-2.0
stcarrez/ada-ado
03e34649700c9933bab5d51410a2a7125b49c620
orka_numerics/src/orka-integrators.ads
orka_numerics/src/orka-integrators.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package Orka.Integrators is pragma Pure; generic type Value is private; type Derivative is private; type Duration_Type is digits <>; with function "*" (Left : Duration_Type; Right : Derivative) return Derivative is <>; with function "+" (Left : Value; Right : Derivative) return Value is <>; with function "+" (Left : Derivative; Right : Derivative) return Derivative is <>; function RK4 (Y : Value; DT : Duration_Type; F : not null access function (Y : Value; DT : Duration_Type) return Derivative) return Derivative; -- Return the change to Y for the given DT time step using -- the Runge-Kutta 4th order method -- -- If F represent a time-variant system, that is, F depends on a time T, -- then you must compute the derivative at time T + DT. In this case you -- must keep track of T yourself and add it to the given DT. -- -- The returned value must be added to Y to perform the numerical integration. -- -- For example, to numerically integrate a position 10 times per second: -- -- X := X + RK4 (X, 0.1, DX'Access); end Orka.Integrators;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. package Orka.Integrators is pragma Preelaborate; generic type Value is private; type Derivative is private; type Duration_Type is digits <>; with function "*" (Left : Duration_Type; Right : Derivative) return Derivative is <>; with function "+" (Left : Value; Right : Derivative) return Value is <>; with function "+" (Left : Derivative; Right : Derivative) return Derivative is <>; function RK4 (Y : Value; DT : Duration_Type; F : not null access function (Y : Value; DT : Duration_Type) return Derivative) return Derivative; -- Return the change to Y for the given DT time step using -- the Runge-Kutta 4th order method -- -- If F represent a time-variant system, that is, F depends on a time T, -- then you must compute the derivative at time T + DT. In this case you -- must keep track of T yourself and add it to the given DT. -- -- The returned value must be added to Y to perform the numerical integration. -- -- For example, to numerically integrate a position 10 times per second: -- -- X := X + RK4 (X, 0.1, DX'Access); end Orka.Integrators;
Make package Orka.Integrators Preelaborate instead of Pure
numerics: Make package Orka.Integrators Preelaborate instead of Pure It might happen that the compiler caches results if the package is Pure, even when the function F returns different values when it represents a time-variant system. Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
bb3fc68a84738fc328c2f48d7abe7280cf4adfae
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean is use type MAT.Types.Target_Size; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Context); when N_AND => return Is_Selected (Node.Left.all, Context) and then Is_Selected (Node.Right.all, Context); when N_OR => return Is_Selected (Node.Left.all, Context) or else Is_Selected (Node.Right.all, Context); when N_RANGE_SIZE => return Context.Allocation.Size >= Node.Min_Size and Context.Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Context.Addr >= Node.Min_Addr and Context.Addr <= Node.Max_Addr; when others => return False; end case; end Is_Selected; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean is begin if Node.Node = null then return False; else return Is_Selected (Node.Node.all, Context); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Context); when N_AND => return Is_Selected (Node.Left.all, Context) and then Is_Selected (Node.Right.all, Context); when N_OR => return Is_Selected (Node.Left.all, Context) or else Is_Selected (Node.Right.all, Context); when N_RANGE_SIZE => return Context.Allocation.Size >= Node.Min_Size and Context.Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Context.Addr >= Node.Min_Addr and Context.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Context.Allocation.Time >= Node.Min_Time and Context.Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; end MAT.Expressions;
Implement the Is_Selected operation on Expression_Type
Implement the Is_Selected operation on Expression_Type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ebd468b17b10c9729752d4c193b65e266ef54501
src/el-methods-func_1.ads
src/el-methods-func_1.ads
----------------------------------------------------------------------- -- EL.Methods.Func_1 -- Function Bindings with 1 argument -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Contexts; with Util.Beans.Methods; with Util.Beans.Basic; generic type Param1_Type (<>) is private; type Return_Type (<>) is private; package EL.Methods.Func_1 is use Util.Beans.Methods; -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- function F (Obj : <Bean>; Param : Param1_Type) return Return_Type; -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. function Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in Param1_Type; Context : in EL.Contexts.ELContext'Class) return Return_Type; -- Function access to the proxy. type Proxy_Access is access function (O : in Util.Beans.Basic.Readonly_Bean'Class; P : in Param1_Type) return Return_Type; -- The binding record which links the method name -- to the proxy function. type Binding is new Method_Binding with record Method : Proxy_Access; end record; type Binding_Access is access constant Binding; -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. generic -- Name of the method (as exposed in the EL expression) Name : String; -- The bean type type Bean is new Util.Beans.Basic.Readonly_Bean with private; -- The bean method to invoke with function Method (O : in Bean; P1 : in Param1_Type) return Return_Type; package Bind is -- Method that <b>Execute</b> will invoke. function Method_Access (O : in Util.Beans.Basic.Readonly_Bean'Class; P1 : in Param1_Type) return Return_Type; F_NAME : aliased constant String := Name; -- The proxy binding that can be exposed through -- the <b>Method_Bean</b> interface. Proxy : aliased constant Binding := Binding '(Name => F_NAME'Access, Method => Method_Access'Access); end Bind; end EL.Methods.Func_1;
----------------------------------------------------------------------- -- EL.Methods.Func_1 -- Function Bindings with 1 argument -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions; with EL.Contexts; with Util.Beans.Methods; with Util.Beans.Basic; generic type Param1_Type (<>) is limited private; type Return_Type (<>) is private; package EL.Methods.Func_1 is use Util.Beans.Methods; -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- function F (Obj : <Bean>; Param : Param1_Type) return Return_Type; -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. function Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in Param1_Type; Context : in EL.Contexts.ELContext'Class) return Return_Type; -- Function access to the proxy. type Proxy_Access is access function (O : in Util.Beans.Basic.Readonly_Bean'Class; P : in Param1_Type) return Return_Type; -- The binding record which links the method name -- to the proxy function. type Binding is new Method_Binding with record Method : Proxy_Access; end record; type Binding_Access is access constant Binding; -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. generic -- Name of the method (as exposed in the EL expression) Name : String; -- The bean type type Bean is new Util.Beans.Basic.Readonly_Bean with private; -- The bean method to invoke with function Method (O : in Bean; P1 : in Param1_Type) return Return_Type; package Bind is -- Method that <b>Execute</b> will invoke. function Method_Access (O : in Util.Beans.Basic.Readonly_Bean'Class; P1 : in Param1_Type) return Return_Type; F_NAME : aliased constant String := Name; -- The proxy binding that can be exposed through -- the <b>Method_Bean</b> interface. Proxy : aliased constant Binding := Binding '(Name => F_NAME'Access, Method => Method_Access'Access); end Bind; end EL.Methods.Func_1;
Change the function parameter to a limited parameter allowing to pass limited types
Change the function parameter to a limited parameter allowing to pass limited types
Ada
apache-2.0
Letractively/ada-el
d81917095ce62101dc4219375a1e314a263e1fd1
src/sys/os-windows/util-systems-os.ads
src/sys/os-windows/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.CR & ASCII.LF; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "GetLastError"); -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; use type Util.Systems.Types.HANDLE; INVALID_HANDLE_VALUE : constant HANDLE := -1; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := 0; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "CloseHandle"); function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype LPCSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := 0; hStdOutput : HANDLE := 0; hStdError : HANDLE := 0; end record; -- pragma Pack (Startup_Info); type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); FILE_SHARE_WRITE : constant DWORD := 16#02#; FILE_SHARE_READ : constant DWORD := 16#01#; GENERIC_READ : constant DWORD := 16#80000000#; GENERIC_WRITE : constant DWORD := 16#40000000#; CREATE_NEW : constant DWORD := 1; CREATE_ALWAYS : constant DWORD := 2; OPEN_EXISTING : constant DWORD := 3; OPEN_ALWAYS : constant DWORD := 4; TRUNCATE_EXISTING : constant DWORD := 5; FILE_APPEND_DATA : constant DWORD := 4; FILE_ATTRIBUTE_ARCHIVE : constant DWORD := 16#20#; FILE_ATTRIBUTE_HIDDEN : constant DWORD := 16#02#; FILE_ATTRIBUTE_NORMAL : constant DWORD := 16#80#; FILE_ATTRIBUTE_READONLY : constant DWORD := 16#01#; FILE_ATTRIBUTE_TEMPORARY : constant DWORD := 16#100#; function Create_File (Name : in LPCTSTR; Desired_Access : in DWORD; Share_Mode : in DWORD; Attributes : in LPSECURITY_ATTRIBUTES; Creation : in DWORD; Flags : in DWORD; Template_File : HANDLE) return HANDLE; pragma Import (Stdcall, Create_File, "CreateFileW"); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.CR & ASCII.LF; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "GetLastError"); -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; use type Util.Systems.Types.HANDLE; INVALID_HANDLE_VALUE : constant HANDLE := -1; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := 0; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "CloseHandle"); function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype LPCSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := 0; hStdOutput : HANDLE := 0; hStdError : HANDLE := 0; end record; -- pragma Pack (Startup_Info); type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t with Import => True, Convention => C, Link_Name => "_lseek"; FILE_SHARE_WRITE : constant DWORD := 16#02#; FILE_SHARE_READ : constant DWORD := 16#01#; GENERIC_READ : constant DWORD := 16#80000000#; GENERIC_WRITE : constant DWORD := 16#40000000#; CREATE_NEW : constant DWORD := 1; CREATE_ALWAYS : constant DWORD := 2; OPEN_EXISTING : constant DWORD := 3; OPEN_ALWAYS : constant DWORD := 4; TRUNCATE_EXISTING : constant DWORD := 5; FILE_APPEND_DATA : constant DWORD := 4; FILE_ATTRIBUTE_ARCHIVE : constant DWORD := 16#20#; FILE_ATTRIBUTE_HIDDEN : constant DWORD := 16#02#; FILE_ATTRIBUTE_NORMAL : constant DWORD := 16#80#; FILE_ATTRIBUTE_READONLY : constant DWORD := 16#01#; FILE_ATTRIBUTE_TEMPORARY : constant DWORD := 16#100#; function Create_File (Name : in LPCTSTR; Desired_Access : in DWORD; Share_Mode : in DWORD; Attributes : in LPSECURITY_ATTRIBUTES; Creation : in DWORD; Flags : in DWORD; Template_File : HANDLE) return HANDLE; pragma Import (Stdcall, Create_File, "CreateFileW"); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
Declare the Sys_Lseek procedure
Declare the Sys_Lseek procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
66bc862facde4e1a8b44cd08dfe7f6b78bdb2868
matp/src/mat-readers-marshaller.adb
matp/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; package body MAT.Readers.Marshaller is use type System.Storage_Elements.Storage_Offset; use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; use type Interfaces.Unsigned_16; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg.Buffer)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg.Buffer)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg.Buffer)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg.Buffer)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Message_Type) return String is Len : constant MAT.Types.Uint16 := Get_Uint16 (Buffer.Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer.Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Message_Type; Size : in Natural) is begin Buffer.Buffer.Size := Buffer.Buffer.Size - Size; Buffer.Buffer.Current := Buffer.Buffer.Current + System.Storage_Elements.Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Uint32); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; function Get_Target_Process_Ref (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Process_Ref is function Get_Value is new Get_Target_Value (MAT.Types.Target_Process_Ref); begin return Get_Value (Msg, Kind); end Get_Target_Process_Ref; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; package body MAT.Readers.Marshaller is use type System.Storage_Elements.Storage_Offset; use type Interfaces.Unsigned_32; use type Interfaces.Unsigned_64; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; use type Interfaces.Unsigned_16; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + System.Storage_Elements.Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + System.Storage_Elements.Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; -- ------------------------------ -- Get a 32-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; -- ------------------------------ -- Get a 64-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Low : MAT.Types.Uint32; High : MAT.Types.Uint32; begin if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint32 (Buffer); High := Get_Uint32 (Buffer); else High := Get_Uint32 (Buffer); Low := Get_Uint32 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint64 (High), 32) + MAT.Types.Uint64 (Low); end Get_Uint64; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg.Buffer)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg.Buffer)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg.Buffer)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg.Buffer)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Message_Type) return String is Len : constant MAT.Types.Uint16 := Get_Uint16 (Buffer.Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer.Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Message_Type; Size : in Natural) is use System.Storage_Elements; begin Buffer.Buffer.Size := Buffer.Buffer.Size - Size; Buffer.Buffer.Current := Buffer.Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Uint32); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; function Get_Target_Process_Ref (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Process_Ref is function Get_Value is new Get_Target_Value (MAT.Types.Target_Process_Ref); begin return Get_Value (Msg, Kind); end Get_Target_Process_Ref; end MAT.Readers.Marshaller;
Fix compilation warning with GNAT 2018
Fix compilation warning with GNAT 2018
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a83c407601ce29e72c4324f9ff543818e36fa835
src/gen-commands-generate.adb
src/gen-commands-generate.adb
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- 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 GNAT.Command_Line; with Ada.Directories; with Ada.Text_IO; package body Gen.Commands.Generate is use GNAT.Command_Line; use Ada.Directories; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); File_Count : Natural := 0; begin Generator.Read_Project ("dynamo.xml"); -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; if Ada.Directories.Exists (Model_File) and then Ada.Directories.Kind (Model_File) = Ada.Directories.Directory then Gen.Generator.Read_Models (Generator, Model_File); else Gen.Generator.Read_Model (Generator, Model_File); end if; end; end loop; if File_Count = 0 then Gen.Generator.Read_Models (Generator, "db"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (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 ("generate: Generate the Ada files for the database model or queries"); Put_Line ("Usage: generate [MODEL ...]"); New_Line; Put_Line (" Read the XML model description (Hibernate mapping, query mapping, ...)"); Put_Line (" and generate the Ada model files that correspond to the mapping."); end Help; end Gen.Commands.Generate;
----------------------------------------------------------------------- -- gen-commands-generate -- Generate command for dynamo -- 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 GNAT.Command_Line; with Ada.Directories; with Ada.Text_IO; package body Gen.Commands.Generate is use GNAT.Command_Line; use Ada.Directories; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); File_Count : Natural := 0; begin Generator.Read_Project ("dynamo.xml", True); -- Read the model files. loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; File_Count := File_Count + 1; if Ada.Directories.Exists (Model_File) and then Ada.Directories.Kind (Model_File) = Ada.Directories.Directory then Gen.Generator.Read_Models (Generator, Model_File); else Gen.Generator.Read_Model (Generator, Model_File); end if; end; end loop; if File_Count = 0 then Gen.Generator.Read_Models (Generator, "db"); end if; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (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 ("generate: Generate the Ada files for the database model or queries"); Put_Line ("Usage: generate [MODEL ...]"); New_Line; Put_Line (" Read the XML model description (Hibernate mapping, query mapping, ...)"); Put_Line (" and generate the Ada model files that correspond to the mapping."); end Help; end Gen.Commands.Generate;
Call the Finish operation after generating the model files
Call the Finish operation after generating the model files
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
97a4660412aeb9853723940209c0cf4614e77f28
src/gen-model-enums.ads
src/gen-model-enums.ads
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Mappings; with Gen.Model.Packages; package Gen.Model.Enums is use Ada.Strings.Unbounded; type Enum_Definition; type Enum_Definition_Access is access all Enum_Definition'Class; -- ------------------------------ -- Enum value definition -- ------------------------------ type Value_Definition is new Definition with record Number : Natural := 0; Enum : Enum_Definition_Access; end record; type Value_Definition_Access is access all Value_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 : Value_Definition; Name : String) return Util.Beans.Objects.Object; -- Compare two enum literals. function "<" (Left, Right : in Value_Definition_Access) return Boolean; package Value_List is new Gen.Model.List (T => Value_Definition, T_Access => Value_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Enum_Definition is new Mappings.Mapping_Definition with record Values : aliased Value_List.List_Definition; Values_Bean : Util.Beans.Objects.Object; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Sql_Type : Unbounded_String; 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 : Enum_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Enum_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Enum_Definition); -- Add an enum value to this enum definition and return the new value. procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access); -- Create an enum with the given name. function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access; end Gen.Model.Enums;
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- Copyright (C) 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Mappings; with Gen.Model.Packages; package Gen.Model.Enums is use Ada.Strings.Unbounded; type Enum_Definition; type Enum_Definition_Access is access all Enum_Definition'Class; -- ------------------------------ -- Enum value definition -- ------------------------------ type Value_Definition is new Definition with record Number : Natural := 0; Enum : Enum_Definition_Access; end record; type Value_Definition_Access is access all Value_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 : Value_Definition; Name : String) return Util.Beans.Objects.Object; -- Compare two enum literals. function "<" (Left, Right : in Value_Definition_Access) return Boolean; package Value_List is new Gen.Model.List (T => Value_Definition, T_Access => Value_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Enum_Definition is new Mappings.Mapping_Definition with record Values : aliased Value_List.List_Definition; Values_Bean : Util.Beans.Objects.Object; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Nullable_Type : Unbounded_String; Pkg_Name : Unbounded_String; Sql_Type : Unbounded_String; 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 : Enum_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Enum_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Enum_Definition); -- Add an enum value to this enum definition and return the new value. procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access); -- Create an enum with the given name. function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access; end Gen.Model.Enums;
Add Nullable_Type member to Enum_Definition record
Add Nullable_Type member to Enum_Definition record
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
7566a8b57281297c2c9d6f438eda416f642b9ade
awa/plugins/awa-votes/src/awa-votes-modules.adb
awa/plugins/awa-votes/src/awa-votes-modules.adb
----------------------------------------------------------------------- -- awa-votes-modules -- Module votes -- 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.Log.Loggers; with Security.Permissions; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Votes.Beans; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Votes.Models; with ADO.SQL; with ADO.Sessions; with ADO.Statements; with ADO.Sessions.Entities; package body AWA.Votes.Modules is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module"); package Register is new AWA.Modules.Beans (Module => Vote_Module, Module_Access => Vote_Module_Access); -- ------------------------------ -- Initialize the votes module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the votes module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Votes.Beans.Votes_Bean", Handler => AWA.Votes.Beans.Create_Vote_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the votes module. -- ------------------------------ function Get_Vote_Module return Vote_Module_Access is function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME); begin return Get; end Get_Vote_Module; -- ------------------------------ -- Vote for the given element and return the total vote for that element. -- ------------------------------ procedure Vote_For (Model : in Vote_Module; Id : in ADO.Identifier; Entity_Type : in String; Permission : in String; Value : in Integer; Total : out Integer) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; Rating : AWA.Votes.Models.Rating_Ref; Vote : AWA.Votes.Models.Vote_Ref; Query : ADO.SQL.Query; Found : Boolean; begin Log.Info ("User {0} votes for {1} rating {2}", ADO.Identifier'Image (User.Get_Id), Entity_Type & ADO.Identifier'Image (Id), Integer'Image (Value)); Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); -- Check that the user has the vote permission on the given object. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Id); -- Get the vote associated with the object for the user. Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id"); Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type " & "and o.user_id = :user_id"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Query.Bind_Param ("user_id", User.Get_Id); Vote.Find (DB, Query, Found); if not Found then Query.Clear; -- Get the rating associated with the object. Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Rating.Find (DB, Query, Found); -- Create it if it does not exist. if not Found then Rating.Set_For_Entity_Id (Id); Rating.Set_For_Entity_Type (Kind); Rating.Set_Rating (Value); Rating.Set_Vote_Count (1); else Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1); Rating.Set_Rating (Value + Rating.Get_Rating); end if; Rating.Save (DB); Vote.Set_User (User); Vote.Set_Entity (Rating); else Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity); Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating); Rating.Save (DB); end if; Vote.Set_Rating (Value); Vote.Save (DB); -- Return the total rating for the element. Total := Rating.Get_Rating; Ctx.Commit; end Vote_For; end AWA.Votes.Modules;
----------------------------------------------------------------------- -- awa-votes-modules -- Module votes -- 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.Log.Loggers; with Security.Permissions; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Votes.Beans; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Votes.Models; with ADO.SQL; with ADO.Sessions; with ADO.Statements; with ADO.Sessions.Entities; package body AWA.Votes.Modules is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module"); package Register is new AWA.Modules.Beans (Module => Vote_Module, Module_Access => Vote_Module_Access); -- ------------------------------ -- Initialize the votes module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the votes module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Votes.Beans.Votes_Bean", Handler => AWA.Votes.Beans.Create_Vote_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the votes module. -- ------------------------------ function Get_Vote_Module return Vote_Module_Access is function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME); begin return Get; end Get_Vote_Module; -- ------------------------------ -- Vote for the given element and return the total vote for that element. -- ------------------------------ procedure Vote_For (Model : in Vote_Module; Id : in ADO.Identifier; Entity_Type : in String; Permission : in String; Value : in Integer; Total : out Integer) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; Rating : AWA.Votes.Models.Rating_Ref; Vote : AWA.Votes.Models.Vote_Ref; Query : ADO.SQL.Query; Found : Boolean; Ident : constant String := Entity_Type & ADO.Identifier'Image (Id); begin Log.Info ("User {0} votes for {1} rating {2}", ADO.Identifier'Image (User.Get_Id), Ident, Integer'Image (Value)); Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type); -- Check that the user has the vote permission on the given object. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Id); -- Get the vote associated with the object for the user. Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id"); Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type " & "and o.user_id = :user_id"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Query.Bind_Param ("user_id", User.Get_Id); Vote.Find (DB, Query, Found); if not Found then -- If the rating is 0, do not create any vote. if Value = 0 then return; end if; Query.Clear; -- Get the rating associated with the object. Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type"); Query.Bind_Param ("id", Id); Query.Bind_Param ("type", Kind); Rating.Find (DB, Query, Found); -- Create it if it does not exist. if not Found then Log.Info ("Creating rating for {0}", Ident); Rating.Set_For_Entity_Id (Id); Rating.Set_For_Entity_Type (Kind); Rating.Set_Rating (Value); Rating.Set_Vote_Count (1); else Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1); Rating.Set_Rating (Value + Rating.Get_Rating); end if; Rating.Save (DB); Vote.Set_User (User); Vote.Set_Entity (Rating); else Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity); Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating); Rating.Save (DB); end if; Vote.Set_Rating (Value); Vote.Save (DB); -- Return the total rating for the element. Total := Rating.Get_Rating; Ctx.Commit; end Vote_For; end AWA.Votes.Modules;
Add a log when the rating is created
Add a log when the rating is created
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
040ac5fd5ff70fdb3b103a2314bd4fff7321de90
src/util-commands.ads
src/util-commands.ads
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Util.Strings.Vectors; package Util.Commands is -- The argument list interface that gives access to command arguments. type Argument_List is limited interface; -- Get the number of arguments available. function Get_Count (List : in Argument_List) return Natural is abstract; -- Get the argument at the given position. function Get_Argument (List : in Argument_List; Pos : in Positive) return String is abstract; -- Get the command name. function Get_Command_Name (List : in Argument_List) return String is abstract; type Default_Argument_List (Offset : Natural) is new Argument_List with null record; -- Get the number of arguments available. overriding function Get_Count (List : in Default_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Default_Argument_List) return String; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with private; -- Set the argument list to the given string and split the arguments. procedure Initialize (List : in out String_Argument_List; Line : in String); -- Get the number of arguments available. overriding function Get_Count (List : in String_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String; -- Get the command name. overriding function Get_Command_Name (List : in String_Argument_List) return String; -- The argument list interface that gives access to command arguments. type Dynamic_Argument_List is limited new Argument_List with private; -- Get the number of arguments available. function Get_Count (List : in Dynamic_Argument_List) return Natural; -- Get the argument at the given position. function Get_Argument (List : in Dynamic_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Dynamic_Argument_List) return String; private type Argument_Pos is array (Natural range <>) of Natural; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with record Count : Natural := 0; Length : Natural := 0; Line : String (1 .. Max_Length); Start_Pos : Argument_Pos (0 .. Max_Args); End_Pos : Argument_Pos (0 .. Max_Args); end record; type Dynamic_Argument_List is limited new Argument_List with record List : Util.Strings.Vectors.Vector; end record; end Util.Commands;
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Util.Strings.Vectors; private with Ada.Strings.Unbounded; package Util.Commands is -- The argument list interface that gives access to command arguments. type Argument_List is limited interface; -- Get the number of arguments available. function Get_Count (List : in Argument_List) return Natural is abstract; -- Get the argument at the given position. function Get_Argument (List : in Argument_List; Pos : in Positive) return String is abstract; -- Get the command name. function Get_Command_Name (List : in Argument_List) return String is abstract; type Default_Argument_List (Offset : Natural) is new Argument_List with null record; -- Get the number of arguments available. overriding function Get_Count (List : in Default_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Default_Argument_List) return String; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with private; -- Set the argument list to the given string and split the arguments. procedure Initialize (List : in out String_Argument_List; Line : in String); -- Get the number of arguments available. overriding function Get_Count (List : in String_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in String_Argument_List; Pos : in Positive) return String; -- Get the command name. overriding function Get_Command_Name (List : in String_Argument_List) return String; -- The argument list interface that gives access to command arguments. type Dynamic_Argument_List is limited new Argument_List with private; -- Get the number of arguments available. function Get_Count (List : in Dynamic_Argument_List) return Natural; -- Get the argument at the given position. function Get_Argument (List : in Dynamic_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Dynamic_Argument_List) return String; private type Argument_Pos is array (Natural range <>) of Natural; type String_Argument_List (Max_Length : Positive; Max_Args : Positive) is new Argument_List with record Count : Natural := 0; Length : Natural := 0; Line : String (1 .. Max_Length); Start_Pos : Argument_Pos (0 .. Max_Args); End_Pos : Argument_Pos (0 .. Max_Args); end record; type Dynamic_Argument_List is limited new Argument_List with record List : Util.Strings.Vectors.Vector; Name : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands;
Add a Name to the Dynamic_Argument_List type for the command name
Add a Name to the Dynamic_Argument_List type for the command name
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f8a75f30963df2132b20e2463bb897ec9d9955be
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Gen.Commands.Usage; return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Gen.Commands.Usage; return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); end Help; end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Gen.Commands.Usage; return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Gen.Commands.Usage; return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); end Help; end Gen.Commands.Project;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d58269f5ee5529046dac92b0e27b2bea7f47c57e
src/util-concurrent-pools.adb
src/util-concurrent-pools.adb
----------------------------------------------------------------------- -- Util.Concurrent.Pools -- Concurrent Pools -- Copyright (C) 2011, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Pools is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ procedure Get_Instance (From : in out Pool; Item : out Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then From.List.Get_Instance (Item); else select From.List.Get_Instance (Item); or delay Wait; raise Timeout; end select; end if; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Into : in out Pool; Item : in Element_Type) is begin Into.List.Release (Item); end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Into : in out Pool; Capacity : in Positive) is begin Into.List.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Get the number of available elements in the pool. -- ------------------------------ procedure Get_Available (From : in out Pool; Available : out Natural) is begin Available := From.List.Get_Available; end Get_Available; -- ------------------------------ -- Release the pool elements. -- ------------------------------ overriding procedure Finalize (Object : in out Pool) is begin Object.List.Set_Size (0); end Finalize; -- Pool of objects protected body Protected_Pool is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ entry Get_Instance (Item : out Element_Type) when Available > 0 is begin Item := Elements (Available); Available := Available - 1; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Item : in Element_Type) is begin Available := Available + 1; Elements (Available) := Item; end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); begin if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (1 .. Capacity); else declare New_Array : constant Element_Array_Access := new Element_Array (1 .. Capacity); begin if Capacity > Elements'Size then New_Array (1 .. Elements'Last) := Elements (1 .. Elements'Last); else New_Array (1 .. Capacity) := Elements (1 .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; -- ------------------------------ -- Get the number of available elements. -- ------------------------------ function Get_Available return Natural is begin return Available; end Get_Available; end Protected_Pool; end Util.Concurrent.Pools;
----------------------------------------------------------------------- -- util-concurrent-pools -- Concurrent Pools -- Copyright (C) 2011, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Concurrent.Pools is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ procedure Get_Instance (From : in out Pool; Item : out Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then From.List.Get_Instance (Item); else select From.List.Get_Instance (Item); or delay Wait; raise Timeout; end select; end if; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Into : in out Pool; Item : in Element_Type) is begin Into.List.Release (Item); end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Into : in out Pool; Capacity : in Positive) is begin Into.List.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Get the number of available elements in the pool. -- ------------------------------ procedure Get_Available (From : in out Pool; Available : out Natural) is begin Available := From.List.Get_Available; end Get_Available; -- ------------------------------ -- Release the pool elements. -- ------------------------------ overriding procedure Finalize (Object : in out Pool) is begin Object.List.Set_Size (0); end Finalize; -- Pool of objects protected body Protected_Pool is -- ------------------------------ -- Get an element instance from the pool. -- Wait until one instance gets available. -- ------------------------------ entry Get_Instance (Item : out Element_Type) when Available > 0 is begin Item := Elements (Available); Available := Available - 1; end Get_Instance; -- ------------------------------ -- Put the element back to the pool. -- ------------------------------ procedure Release (Item : in Element_Type) is begin Available := Available + 1; Elements (Available) := Item; end Release; -- ------------------------------ -- Set the pool size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); begin if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (1 .. Capacity); else declare New_Array : constant Element_Array_Access := new Element_Array (1 .. Capacity); begin if Capacity > Elements'Size then New_Array (1 .. Elements'Last) := Elements (1 .. Elements'Last); else New_Array (1 .. Capacity) := Elements (1 .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; -- ------------------------------ -- Get the number of available elements. -- ------------------------------ function Get_Available return Natural is begin return Available; end Get_Available; end Protected_Pool; end Util.Concurrent.Pools;
Update the header
Update the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
95880958f105d4b3a56bfffe99308c2e53c9554b
src/util-processes-tools.ads
src/util-processes-tools.ads
----------------------------------------------------------------------- -- util-processes-tools -- System specific and low level operations -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; package Util.Processes.Tools is -- Execute the command and append the output in the vector array. -- The program output is read line by line and the standard input is closed. -- Return the program exit status. procedure Execute (Command : in String; Output : in out Util.Strings.Vectors.Vector; Status : out Integer); end Util.Processes.Tools;
----------------------------------------------------------------------- -- util-processes-tools -- System specific and low level operations -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with Util.Streams.Pipes; package Util.Processes.Tools is -- Execute the command and append the output in the vector array. -- The program output is read line by line and the standard input is closed. -- Return the program exit status. procedure Execute (Command : in String; Output : in out Util.Strings.Vectors.Vector; Status : out Integer); procedure Execute (Command : in String; Input_Path : in String; Output : in out Util.Strings.Vectors.Vector; Status : out Integer); procedure Execute (Command : in String; Process : in out Util.Streams.Pipes.Pipe_Stream; Output : in out Util.Strings.Vectors.Vector; Status : out Integer); end Util.Processes.Tools;
Declare more Execute procedures as helper to launch a command and get the output
Declare more Execute procedures as helper to launch a command and get the output
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
80eede101af509e5afe085754b06a83d555554a2
testutil/ahven/util-xunit.adb
testutil/ahven/util-xunit.adb
----------------------------------------------------------------------- -- util-xunit - Unit tests on top of AHven -- 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.Directories; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Calendar; with Ahven.Listeners.Basic; with Ahven.XML_Runner; with Ahven.Text_Runner; with Util.Tests; package body Util.XUnit is -- ------------------------------ -- Build a message from a string (Adaptation for AUnit API). -- ------------------------------ function Format (S : in String) return Message_String is begin return S; end Format; -- ------------------------------ -- Build a message with the source and line number. -- ------------------------------ function Build_Message (Message : in String; Source : in String; Line : in Natural) return String is L : constant String := Natural'Image (Line); begin return Source & ":" & L (2 .. L'Last) & ": " & Message; end Build_Message; procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class); procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class) is begin Test_Case'Class (T).Run_Test; end Run_Test_Case; overriding procedure Initialize (T : in out Test_Case) is begin Ahven.Framework.Add_Test_Routine (T, Run_Test_Case'Access, "Test case"); end Initialize; -- ------------------------------ -- Return the name of the test case. -- ------------------------------ overriding function Get_Name (T : Test_Case) return String is begin return Test_Case'Class (T).Name; end Get_Name; -- maybe_overriding procedure Assert (T : in Test_Case; Condition : in Boolean; Message : in String := "Test failed"; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; -- ------------------------------ -- Check that the value matches what we expect. -- ------------------------------ procedure Assert (T : in Test; Condition : in Boolean; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; First_Test : Test_Object_Access := null; -- ------------------------------ -- Register a test object in the test suite. -- ------------------------------ procedure Register (T : in Test_Object_Access) is begin T.Next := First_Test; First_Test := T; end Register; -- ------------------------------ -- Report passes, skips, failures, and errors from the result collection. -- ------------------------------ procedure Report_Results (Result : in Ahven.Results.Result_Collection; Time : in Duration) is T_Count : constant Integer := Ahven.Results.Test_Count (Result); F_Count : constant Integer := Ahven.Results.Failure_Count (Result); S_Count : constant Integer := Ahven.Results.Skipped_Count (Result); E_Count : constant Integer := Ahven.Results.Error_Count (Result); begin if F_Count > 0 then Ahven.Text_Runner.Print_Failures (Result, 0); end if; if E_Count > 0 then Ahven.Text_Runner.Print_Errors (Result, 0); end if; Ada.Text_IO.Put_Line ("Tests run:" & Integer'Image (T_Count - S_Count) & ", Failures:" & Integer'Image (F_Count) & ", Errors:" & Integer'Image (E_Count) & ", Skipped:" & Integer'Image (S_Count) & ", Time elapsed:" & Duration'Image (Time)); end Report_Results; -- ------------------------------ -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. -- ------------------------------ procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String; XML : in Boolean; Result : out Status) is pragma Unreferenced (XML, Output); use Ahven.Listeners.Basic; use Ahven.Framework; use Ahven.Results; use type Ada.Calendar.Time; Tests : constant Access_Test_Suite := Suite; T : Test_Object_Access := First_Test; Listener : Ahven.Listeners.Basic.Basic_Listener; Timeout : constant Test_Duration := Test_Duration (Util.Tests.Get_Test_Timeout ("all")); Out_Dir : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Start : Ada.Calendar.Time; begin while T /= null loop Ahven.Framework.Add_Static_Test (Tests.all, T.Test.all); T := T.Next; end loop; Set_Output_Capture (Listener, True); if not Ada.Directories.Exists (Out_Dir) then Ada.Directories.Create_Path (Out_Dir); end if; Start := Ada.Calendar.Clock; Ahven.Framework.Execute (Tests.all, Listener, Timeout); Report_Results (Listener.Main_Result, Ada.Calendar.Clock - Start); Ahven.XML_Runner.Report_Results (Listener.Main_Result, Out_Dir); if (Error_Count (Listener.Main_Result) > 0) or (Failure_Count (Listener.Main_Result) > 0) then Result := Failure; else Result := Success; end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot create file"); Result := Failure; end Harness; end Util.XUnit;
----------------------------------------------------------------------- -- util-xunit - Unit tests on top of AHven -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Calendar; with Ahven.Listeners.Basic; with Ahven.XML_Runner; with Ahven.Text_Runner; with Util.Tests; package body Util.XUnit is -- ------------------------------ -- Build a message from a string (Adaptation for AUnit API). -- ------------------------------ function Format (S : in String) return Message_String is begin return S; end Format; -- ------------------------------ -- Build a message with the source and line number. -- ------------------------------ function Build_Message (Message : in String; Source : in String; Line : in Natural) return String is L : constant String := Natural'Image (Line); begin return Source & ":" & L (2 .. L'Last) & ": " & Message; end Build_Message; procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class); procedure Run_Test_Case (T : in out Ahven.Framework.Test_Case'Class) is begin Test_Case'Class (T).Run_Test; end Run_Test_Case; overriding procedure Initialize (T : in out Test_Case) is begin Ahven.Framework.Add_Test_Routine (T, Run_Test_Case'Access, "Test case"); end Initialize; -- ------------------------------ -- Return the name of the test case. -- ------------------------------ overriding function Get_Name (T : Test_Case) return String is begin return Test_Case'Class (T).Name; end Get_Name; -- maybe_overriding procedure Assert (T : in Test_Case; Condition : in Boolean; Message : in String := "Test failed"; Source : in String := GNAT.Source_Info.File; Line : in Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; -- ------------------------------ -- Check that the value matches what we expect. -- ------------------------------ procedure Assert (T : in Test; Condition : in Boolean; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is pragma Unreferenced (T); begin Ahven.Assert (Condition => Condition, Message => Build_Message (Message => Message, Source => Source, Line => Line)); end Assert; First_Test : Test_Object_Access := null; -- ------------------------------ -- Register a test object in the test suite. -- ------------------------------ procedure Register (T : in Test_Object_Access) is begin T.Next := First_Test; First_Test := T; end Register; -- ------------------------------ -- Report passes, skips, failures, and errors from the result collection. -- ------------------------------ procedure Report_Results (Result : in Ahven.Results.Result_Collection; Time : in Duration) is T_Count : constant Integer := Ahven.Results.Test_Count (Result); F_Count : constant Integer := Ahven.Results.Failure_Count (Result); S_Count : constant Integer := Ahven.Results.Skipped_Count (Result); E_Count : constant Integer := Ahven.Results.Error_Count (Result); begin if F_Count > 0 then Ahven.Text_Runner.Print_Failures (Result, 0); end if; if E_Count > 0 then Ahven.Text_Runner.Print_Errors (Result, 0); end if; Ada.Text_IO.Put_Line ("Tests run:" & Integer'Image (T_Count - S_Count) & ", Failures:" & Integer'Image (F_Count) & ", Errors:" & Integer'Image (E_Count) & ", Skipped:" & Integer'Image (S_Count) & ", Time elapsed:" & Duration'Image (Time)); end Report_Results; -- ------------------------------ -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. -- ------------------------------ procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String; XML : in Boolean; Result : out Status) is pragma Unreferenced (XML, Output); use Ahven.Listeners.Basic; use Ahven.Framework; use Ahven.Results; use type Ada.Calendar.Time; Tests : constant Access_Test_Suite := Suite; T : Test_Object_Access := First_Test; Listener : Ahven.Listeners.Basic.Basic_Listener; Timeout : constant Test_Duration := Test_Duration (Util.Tests.Get_Test_Timeout ("all")); Out_Dir : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Start : Ada.Calendar.Time; begin while T /= null loop Ahven.Framework.Add_Static_Test (Tests.all, T.Test.all); T := T.Next; end loop; Set_Output_Capture (Listener, True); if not Ada.Directories.Exists (Out_Dir) then Ada.Directories.Create_Path (Out_Dir); end if; Start := Ada.Calendar.Clock; Ahven.Framework.Execute (Tests.all, Listener, Timeout); Report_Results (Listener.Main_Result, Ada.Calendar.Clock - Start); Ahven.XML_Runner.Report_Results (Listener.Main_Result, Out_Dir); if (Error_Count (Listener.Main_Result) > 0) or (Failure_Count (Listener.Main_Result) > 0) then Result := Failure; else Result := Success; end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot create file"); Result := Failure; end Harness; end Util.XUnit;
Fix indentation
Fix indentation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
de3e6b147a1c72ac27518af7d8b58ea6107fdacb
regtests/util-streams-sockets-tests.adb
regtests/util-streams-sockets-tests.adb
----------------------------------------------------------------------- -- util-streams-sockets-tests -- Unit tests for socket streams -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.IO_Exceptions; with Util.Test_Caller; with Util.Streams.Texts; with Util.Tests.Servers; package body Util.Streams.Sockets.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Streams.Sockets"); type Test_Server is new Util.Tests.Servers.Server with record Count : Natural := 0; end record; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect", Test_Socket_Init'Access); Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write", Test_Socket_Read'Access); end Add_Tests; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String) is begin if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then Into.Count := Into.Count + 1; end if; end Process_Line; -- ------------------------------ -- Test reading and writing on a socket stream. -- ------------------------------ procedure Test_Socket_Read (T : in out Test) is Stream : aliased Sockets.Socket_Stream; Writer : Util.Streams.Texts.Print_Stream; Server : Test_Server; Addr : GNAT.Sockets.Sock_Addr_Type; begin Server.Start; T.Assert (Server.Get_Port > 0, "The server was not started"); Addr := (GNAT.Sockets.Family_Inet, GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1), GNAT.Sockets.Port_Type (Server.Get_Port)); -- Let the server start. delay 0.1; -- Get a connection and write 10 lines. Stream.Connect (Server => Addr); Writer.Initialize (Output => Stream'Unchecked_Access, Input => null, Size => 1024); for I in 1 .. 10 loop Writer.Write ("Sending a line on the socket test-" & Natural'Image (I) & ASCII.CR & ASCII.LF); Writer.Flush; end loop; Writer.Close; -- Stop the server and verify that 10 lines were received. Server.Stop; Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received"); end Test_Socket_Read; -- ------------------------------ -- Test socket initialization. -- ------------------------------ procedure Test_Socket_Init (T : in out Test) is Stream : aliased Sockets.Socket_Stream; Fd : GNAT.Sockets.Socket_Type; Addr : GNAT.Sockets.Sock_Addr_Type; begin Addr := (GNAT.Sockets.Family_Inet, GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1), 80); GNAT.Sockets.Create_Socket (Fd); Stream.Open (Fd); begin Stream.Connect (Addr); T.Assert (False, "No exception was raised"); exception when Ada.IO_Exceptions.Use_Error => null; end; end Test_Socket_Init; end Util.Streams.Sockets.Tests;
----------------------------------------------------------------------- -- util-streams-sockets-tests -- Unit tests for socket streams -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.IO_Exceptions; with Util.Test_Caller; with Util.Streams.Texts; with Util.Tests.Servers; package body Util.Streams.Sockets.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Streams.Sockets"); type Test_Server is new Util.Tests.Servers.Server with record Count : Natural := 0; end record; -- Process the line received by the server. overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Initialize,Connect", Test_Socket_Init'Access); Caller.Add_Test (Suite, "Test Util.Streams.Connect,Read,Write", Test_Socket_Read'Access); end Add_Tests; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ overriding procedure Process_Line (Into : in out Test_Server; Line : in Ada.Strings.Unbounded.Unbounded_String; Stream : in out Util.Streams.Texts.Reader_Stream'Class) is pragma Unreferenced (Stream); begin if Ada.Strings.Unbounded.Index (Line, "test-" & Natural'Image (Into.Count + 1)) > 0 then Into.Count := Into.Count + 1; end if; end Process_Line; -- ------------------------------ -- Test reading and writing on a socket stream. -- ------------------------------ procedure Test_Socket_Read (T : in out Test) is Stream : aliased Sockets.Socket_Stream; Writer : Util.Streams.Texts.Print_Stream; Server : Test_Server; Addr : GNAT.Sockets.Sock_Addr_Type; begin Server.Start; T.Assert (Server.Get_Port > 0, "The server was not started"); Addr := (GNAT.Sockets.Family_Inet, GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1), GNAT.Sockets.Port_Type (Server.Get_Port)); -- Let the server start. delay 0.1; -- Get a connection and write 10 lines. Stream.Connect (Server => Addr); Writer.Initialize (Output => Stream'Unchecked_Access, Input => null, Size => 1024); for I in 1 .. 10 loop Writer.Write ("Sending a line on the socket test-" & Natural'Image (I) & ASCII.CR & ASCII.LF); Writer.Flush; end loop; Writer.Close; -- Stop the server and verify that 10 lines were received. Server.Stop; Util.Tests.Assert_Equals (T, 10, Server.Count, "Invalid number of lines received"); end Test_Socket_Read; -- ------------------------------ -- Test socket initialization. -- ------------------------------ procedure Test_Socket_Init (T : in out Test) is Stream : aliased Sockets.Socket_Stream; Fd : GNAT.Sockets.Socket_Type; Addr : GNAT.Sockets.Sock_Addr_Type; begin Addr := (GNAT.Sockets.Family_Inet, GNAT.Sockets.Addresses (GNAT.Sockets.Get_Host_By_Name (GNAT.Sockets.Host_Name), 1), 80); GNAT.Sockets.Create_Socket (Fd); Stream.Open (Fd); begin Stream.Connect (Addr); T.Assert (False, "No exception was raised"); exception when Ada.IO_Exceptions.Use_Error => null; end; end Test_Socket_Init; end Util.Streams.Sockets.Tests;
Update the unit test
Update the unit test
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
416fb1e874900332dad5d135530facceb54484c7
regtests/asf-contexts-writer-tests.adb
regtests/asf-contexts-writer-tests.adb
----------------------------------------------------------------------- -- Writer Tests - Unit tests for ASF.Contexts.Writer -- 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 Ada.Calendar; with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Test_Caller; package body ASF.Contexts.Writer.Tests is use Util.Tests; procedure Free_Writer is new Ada.Unchecked_Deallocation (Object => Test_Writer'Class, Name => Test_Writer_Access); procedure Initialize (Stream : in out Test_Writer; Content_Type : in String; Encoding : in String; Size : in Natural) is Output : ASF.Streams.Print_Stream; begin Stream.Content.Initialize (Size => Size); Output.Initialize (Stream.Content'Unchecked_Access); Stream.Initialize (Content_Type, Encoding, Output); end Initialize; overriding procedure Write (Stream : in out Test_Writer; Buffer : in Ada.Streams.Stream_Element_Array) is begin for I in Buffer'Range loop Append (Stream.Response, Character'Val (Buffer (I))); end loop; end Write; overriding procedure Flush (Stream : in out Test_Writer) is begin Response_Writer (Stream).Flush; Stream.Content.Read (Into => Stream.Response); end Flush; -- Set up performed before each test case overriding procedure Set_Up (T : in out Test) is begin T.Writer := new Test_Writer; -- use a small buffer to test the flush T.Writer.Initialize ("text/xml", "UTF-8", 1024); end Set_Up; -- Tear down performed after each test case overriding procedure Tear_Down (T : in out Test) is begin Free_Writer (T.Writer); end Tear_Down; -- Test the Start/Write/End_Element methods procedure Test_Write_Element (T : in out Test) is begin T.Writer.Start_Element ("p"); T.Writer.Start_Element ("b"); T.Writer.Write_Element ("i", "italic within a bold"); T.Writer.End_Element ("b"); T.Writer.End_Element ("p"); T.Writer.Flush; Assert_Equals (T, "<p><b><i>italic within a bold</i></b></p>", T.Writer.Response); T.Writer.Response := To_Unbounded_String (""); T.Writer.Start_Element ("div"); T.Writer.Write_Attribute ("title", "A ""S&'%^&<>"); T.Writer.Write_Attribute ("id", "23"); T.Writer.End_Element ("div"); T.Writer.Flush; Assert_Equals (T, "<div title=""A &quot;S&amp;'%^&amp;&lt;&gt;"" id=""23""></div>", T.Writer.Response); end Test_Write_Element; -- Test the Write_Char/Text methods procedure Test_Write_Text (T : in out Test) is use Ada.Calendar; Start : Ada.Calendar.Time; D : Duration; begin Start := Ada.Calendar.Clock; T.Writer.Start_Element ("p"); T.Writer.Write_Char ('<'); T.Writer.Write_Char ('>'); T.Writer.Write_Char ('~'); T.Writer.Start_Element ("i"); T.Writer.Write_Text ("""A' <>&"); T.Writer.End_Element ("i"); T.Writer.End_Element ("p"); T.Writer.Flush; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Write text: " & Duration'Image (D)); Assert_Equals (T, "<p>&lt;&gt;~<i>""A' &lt;&gt;&amp;</i></p>", T.Writer.Response); end Test_Write_Text; package Caller is new Util.Test_Caller (Test, "Contexts.Writer"); 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.Contexts.Writer.Start_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.End_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Attribute", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Text", Test_Write_Text'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Char", Test_Write_Text'Access); end Add_Tests; end ASF.Contexts.Writer.Tests;
----------------------------------------------------------------------- -- Writer Tests - Unit tests for ASF.Contexts.Writer -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Ada.Unchecked_Deallocation; with Util.Test_Caller; package body ASF.Contexts.Writer.Tests is use Util.Tests; procedure Free_Writer is new Ada.Unchecked_Deallocation (Object => Test_Writer'Class, Name => Test_Writer_Access); procedure Initialize (Stream : in out Test_Writer; Content_Type : in String; Encoding : in String; Size : in Natural) is Output : ASF.Streams.Print_Stream; begin Stream.Content.Initialize (Size => Size); Output.Initialize (Stream.Content'Unchecked_Access); Stream.Initialize (Content_Type, Encoding, Output); end Initialize; overriding procedure Write (Stream : in out Test_Writer; Buffer : in Ada.Streams.Stream_Element_Array) is begin for I in Buffer'Range loop Append (Stream.Response, Character'Val (Buffer (I))); end loop; end Write; overriding procedure Flush (Stream : in out Test_Writer) is begin Response_Writer (Stream).Flush; Stream.Content.Read (Into => Stream.Response); end Flush; -- Set up performed before each test case overriding procedure Set_Up (T : in out Test) is begin T.Writer := new Test_Writer; -- use a small buffer to test the flush T.Writer.Initialize ("text/xml", "UTF-8", 1024); end Set_Up; -- Tear down performed after each test case overriding procedure Tear_Down (T : in out Test) is begin Free_Writer (T.Writer); end Tear_Down; -- Test the Start/Write/End_Element methods procedure Test_Write_Element (T : in out Test) is begin T.Writer.Start_Element ("p"); T.Writer.Start_Element ("b"); T.Writer.Write_Element ("i", "italic within a bold"); T.Writer.End_Element ("b"); T.Writer.End_Element ("p"); T.Writer.Flush; Assert_Equals (T, "<p><b><i>italic within a bold</i></b></p>", T.Writer.Response); T.Writer.Response := To_Unbounded_String (""); T.Writer.Start_Element ("div"); T.Writer.Write_Attribute ("title", "A ""S&'%^&<>"); T.Writer.Write_Attribute ("id", "23"); T.Writer.End_Element ("div"); T.Writer.Flush; Assert_Equals (T, "<div title=""A &quot;S&amp;'%^&amp;&lt;&gt;"" id=""23""></div>", T.Writer.Response); end Test_Write_Element; -- Test the Write_Char/Text methods procedure Test_Write_Text (T : in out Test) is use Ada.Calendar; Start : Ada.Calendar.Time; D : Duration; begin Start := Ada.Calendar.Clock; T.Writer.Start_Element ("p"); T.Writer.Write_Char ('<'); T.Writer.Write_Char ('>'); T.Writer.Write_Char ('~'); T.Writer.Start_Element ("i"); T.Writer.Write_Text ("""A' <>&"); T.Writer.End_Element ("i"); T.Writer.End_Element ("p"); T.Writer.Flush; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Write text: " & Duration'Image (D)); Assert_Equals (T, "<p>&lt;&gt;~<i>""A' &lt;&gt;&amp;</i></p>", T.Writer.Response); end Test_Write_Text; package Caller is new Util.Test_Caller (Test, "Contexts.Writer"); 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.Contexts.Writer.Start_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.End_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Attribute", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Text", Test_Write_Text'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Char", Test_Write_Text'Access); end Add_Tests; end ASF.Contexts.Writer.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d3aa8645d4d29fd834d6ef66d3c5201af2694f78
regtests/ado-drivers-tests.adb
regtests/ado-drivers-tests.adb
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Databases; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use ADO.Databases; C : ADO.Databases.Connection; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (ADO.Databases.Get_Status (C) = ADO.Databases.CLOSED, "The database connection must be closed for an empty connection"); Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, null); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, "select"); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. begin T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); exception when NOT_OPEN => null; end; end Test_Empty_Connection; end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Test_Caller; with ADO.Statements; with ADO.Databases; with ADO.Drivers.Connections; package body ADO.Drivers.Tests is use ADO.Drivers.Connections; package Caller is new Util.Test_Caller (Test, "ADO.Drivers"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Drivers.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Config", Test_Get_Config'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Get_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver_Index", Test_Get_Driver_Index'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Get_Driver", Test_Load_Invalid_Driver'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection", Test_Set_Connection'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Connection (Errors)", Test_Set_Connection_Error'Access); Caller.Add_Test (Suite, "Test ADO.Drivers.Connections.Set_Server", Test_Set_Connection_Server'Access); Caller.Add_Test (Suite, "Test ADO.Databases (Errors)", Test_Empty_Connection'Access); end Add_Tests; -- ------------------------------ -- Test the Initialize operation. -- ------------------------------ procedure Test_Initialize (T : in out Test) is pragma Unreferenced (T); begin ADO.Drivers.Initialize ("test-missing-config.properties"); end Test_Initialize; -- ------------------------------ -- Test the Get_Config operation. -- ------------------------------ procedure Test_Get_Config (T : in out Test) is begin T.Assert (ADO.Drivers.Get_Config ("test.database")'Length > 0, "The Get_Config operation returned no value for the test database"); end Test_Get_Config; -- ------------------------------ -- Test the Get_Driver operation. -- ------------------------------ procedure Test_Get_Driver (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin T.Assert (Mysql_Driver /= null or Sqlite_Driver /= null, "No database driver was found!"); end Test_Get_Driver; -- ------------------------------ -- Test loading some invalid database driver. -- ------------------------------ procedure Test_Load_Invalid_Driver (T : in out Test) is Invalid_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("invalid"); begin T.Assert (Invalid_Driver = null, "The Get_Driver operation must return null for invalid drivers"); end Test_Load_Invalid_Driver; -- ------------------------------ -- Test the Get_Driver_Index operation. -- ------------------------------ procedure Test_Get_Driver_Index (T : in out Test) is Mysql_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Drivers.Connections.Get_Driver ("sqlite"); begin if Mysql_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Sqlite_Driver /= null then T.Assert (Sqlite_Driver.Get_Driver_Index > 0, "The driver index must be positive"); end if; if Mysql_Driver /= null and Sqlite_Driver /= null then T.Assert (Mysql_Driver.Get_Driver_Index /= Sqlite_Driver.Get_Driver_Index, "Two drivers must have different driver indexes"); end if; end Test_Get_Driver_Index; -- ------------------------------ -- Test the Set_Connection procedure. -- ------------------------------ procedure Test_Set_Connection (T : in out Test) is procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String); procedure Check (URI : in String; Server : in String; Port : in Integer; Database : in String) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection (URI); Util.Tests.Assert_Equals (T, Server, Controller.Get_Server, "Invalid server for " & URI); Util.Tests.Assert_Equals (T, Port, Controller.Get_Port, "Invalid port for " & URI); Util.Tests.Assert_Equals (T, Database, Controller.Get_Database, "Invalid db for " & URI); Controller.Set_Property ("password", "test"); Util.Tests.Assert_Equals (T, "test", Controller.Get_Property ("password"), "Invalid 'password' property for " & URI); exception when E : Connection_Error => Util.Tests.Assert_Matches (T, "Driver.*not found.*", Ada.Exceptions.Exception_Message (E), "Invalid exception raised for " & URI); end Check; begin Check ("mysql://test:3306/db", "test", 3306, "db"); Check ("mysql://test2:3307/db2?user=admin&password=admin", "test2", 3307, "db2"); Check ("sqlite:///test.db", "", 0, "test.db"); Check ("sqlite:///test2.db?user=root&encoding=UTF-8", "", 0, "test2.db"); end Test_Set_Connection; -- ------------------------------ -- Test the Set_Connection procedure with several error cases. -- ------------------------------ procedure Test_Set_Connection_Error (T : in out Test) is procedure Check_Invalid_Connection (URI : in String); Controller : ADO.Drivers.Connections.Configuration; procedure Check_Invalid_Connection (URI : in String) is begin Controller.Set_Connection (URI); T.Fail ("No Connection_Error exception raised for " & URI); exception when Connection_Error => null; end Check_Invalid_Connection; begin Check_Invalid_Connection (""); Check_Invalid_Connection ("http://"); Check_Invalid_Connection ("mysql://"); Check_Invalid_Connection ("sqlite://"); Check_Invalid_Connection ("mysql://:toto/"); Check_Invalid_Connection ("sqlite://:toto/"); end Test_Set_Connection_Error; -- ------------------------------ -- Test the Set_Server operation. -- ------------------------------ procedure Test_Set_Connection_Server (T : in out Test) is Controller : ADO.Drivers.Connections.Configuration; begin Controller.Set_Connection ("mysql://localhost:3306/db"); Controller.Set_Server ("server-name"); Util.Tests.Assert_Equals (T, "server-name", Controller.Get_Server, "Configuration Set_Server returned invalid value"); end Test_Set_Connection_Server; -- ------------------------------ -- Test the connection operations on an empty connection. -- ------------------------------ procedure Test_Empty_Connection (T : in out Test) is use ADO.Databases; C : ADO.Databases.Connection; Stmt : ADO.Statements.Query_Statement; pragma Unreferenced (Stmt); begin T.Assert (ADO.Databases.Get_Status (C) = ADO.Databases.CLOSED, "The database connection must be closed for an empty connection"); Util.Tests.Assert_Equals (T, "null", ADO.Databases.Get_Ident (C), "Get_Ident must return null"); -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, null); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Create_Statement must raise NOT_OPEN. begin Stmt := ADO.Databases.Create_Statement (C, "select"); T.Fail ("No exception raised for Create_Statement"); exception when NOT_OPEN => null; end; -- Get_Driver must raise NOT_OPEN. begin T.Assert (ADO.Databases.Get_Driver (C) /= null, "Get_Driver must raise an exception"); exception when NOT_OPEN => null; end; end Test_Empty_Connection; end ADO.Drivers.Tests;
Implement Test_Set_Connection_Server procedure
Implement Test_Set_Connection_Server procedure
Ada
apache-2.0
stcarrez/ada-ado
ab9833ae716f1e65fc7b67a89b9671068693b2f1
Ada/src/Problem_74.adb
Ada/src/Problem_74.adb
with Ada.Text_IO; package body Problem_74 is package IO renames Ada.Text_IO; procedure Solve is begin IO.Put_Line("The Answer"); end Solve; end Problem_74;
with Ada.Text_IO; package body Problem_74 is package IO renames Ada.Text_IO; factorial_cache : constant Array(0 .. 9) of Integer := (1, 1, 2, 6, 24, 120, 720, 5_040, 40_320, 362_880); type count is new Integer range -1 .. 127; for count'size use 8; type count_cache_array is Array(Positive range <>) of count; max : constant := 999_999; cache_size : constant := 362_880 * 6; count_cache : count_cache_array(1 .. cache_size) := (169 => 3, 871 => 2, 872 => 2, 1454 => 3, 363_601 => 3, 45_361 => 2, 45362 => 2, others => -1); sixty_count : Integer := 0; -- Dynamic programming brute force. Make a 2 megabyte array of counts with sentinal value (-1) -- for values we haven't seen before. Then just go through all the numbers and get their -- count. We were told in the problem description that the the longest chain is 60, so we know -- our stack won't die under the recursion. procedure Solve is function next(num : Positive) return Positive is f : Natural := 0; r : Natural range 0 .. 9; d : Positive := num; begin loop r := d mod 10; f := f + factorial_cache(r); exit when d < 10; d := d / 10; end loop; return f; end next; function fill(num : Positive) return count is next_num : constant Positive := next(num); begin if count_cache(num) = -1 then if next_num = num then count_cache(num) := 1; else count_cache(num) := 0; count_cache(num) := fill(next_num) + 1; end if; end if; return count_cache(num); end fill; begin for n in 2 .. max loop if fill(n) = 60 then sixty_count := sixty_count + 1; end if; end loop; IO.Put_Line(Integer'Image(sixty_count)); end Solve; end Problem_74;
Implement Problem 74.
Implement Problem 74.
Ada
unlicense
Tim-Tom/project-euler,Tim-Tom/project-euler,Tim-Tom/project-euler
c3ba204d21c79d4e71d41976b56697591d684b7b
src/sys/encoders/util-encoders-sha1.ads
src/sys/encoders/util-encoders-sha1.ads
----------------------------------------------------------------------- -- util-encoders-sha1 -- Compute SHA-1 hash -- Copyright (C) 2011, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Interfaces; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.SHA1 is pragma Preelaborate; HASH_SIZE : constant := 20; -- The SHA-1 binary hash (160-bit). subtype Hash_Array is Ada.Streams.Stream_Element_Array (0 .. HASH_SIZE - 1); -- The SHA-1 hash as hexadecimal string. subtype Digest is String (1 .. 2 * HASH_SIZE); subtype Base64_Digest is String (1 .. 28); -- ------------------------------ -- SHA1 Context -- ------------------------------ type Context is limited private; -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the SHA1 hash and returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Hash_Array); -- Computes the SHA1 hash and returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Digest); -- Computes the SHA1 hash and returns the base64 hash in <b>Hash</b>. procedure Finish_Base64 (E : in out Context; Hash : out Base64_Digest); -- ------------------------------ -- SHA1 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Util.Encoders.Transformer with null record; use Interfaces; type H_Array is array (0 .. 4) of Unsigned_32; type W_Array is array (0 .. 79) of Unsigned_32; -- Process the message block collected in the context. procedure Compute (Ctx : in out Context); type Context is new Ada.Finalization.Limited_Controlled with record W : W_Array; H : H_Array; Pos : Natural; Count : Unsigned_64; Pending : String (1 .. 3); Pending_Pos : Natural; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.SHA1;
----------------------------------------------------------------------- -- util-encoders-sha1 -- Compute SHA-1 hash -- Copyright (C) 2011, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Interfaces; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.SHA1 is pragma Preelaborate; HASH_SIZE : constant := 20; -- The SHA-1 binary hash (160-bit). subtype Hash_Array is Ada.Streams.Stream_Element_Array (0 .. HASH_SIZE - 1); -- The SHA-1 hash as hexadecimal string. subtype Digest is String (1 .. 2 * HASH_SIZE); subtype Base64_Digest is String (1 .. 28); -- ------------------------------ -- SHA1 Context -- ------------------------------ type Context is limited private; -- Update the hash with the string. procedure Update (E : in out Context; S : in String); -- Update the hash with the string. procedure Update (E : in out Context; S : in Ada.Streams.Stream_Element_Array); -- Computes the SHA1 hash and returns the raw binary hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Hash_Array); -- Computes the SHA1 hash and returns the hexadecimal hash in <b>Hash</b>. procedure Finish (E : in out Context; Hash : out Digest); -- Computes the SHA1 hash and returns the base64 hash in <b>Hash</b>. procedure Finish_Base64 (E : in out Context; Hash : out Base64_Digest); -- ------------------------------ -- SHA1 encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Util.Encoders.Transformer with private; -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); private type Encoder is new Util.Encoders.Transformer with null record; use Interfaces; type H_Array is array (0 .. 4) of Unsigned_32; type W_Array is array (0 .. 79) of Unsigned_32; -- Process the message block collected in the context. procedure Compute (Ctx : in out Context); type Context is new Ada.Finalization.Limited_Controlled with record W : W_Array; H : H_Array; Pos : Natural; Count : Unsigned_64; Pending : String (1 .. 3); Pending_Pos : Natural; end record; -- Initialize the SHA-1 context. overriding procedure Initialize (E : in out Context); end Util.Encoders.SHA1;
Remove unused with Ada.Streams clause
Remove unused with Ada.Streams clause
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8c5571f1d6693d9462365890612c44dd91a5e63d
src/asf-components-core.adb
src/asf-components-core.adb
----------------------------------------------------------------------- -- components-core -- ASF Core Components -- 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.Beans.Objects; with Ada.Unchecked_Deallocation; package body ASF.Components.Core is use ASF; use EL.Objects; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Return a client-side identifier for this component, generating -- one if necessary. -- ------------------------------ function Get_Client_Id (UI : UIComponentBase) return Unbounded_String is Id : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("id"); begin if Id /= null then return To_Unbounded_String (Views.Nodes.Get_Value (Id.all, UI.Get_Context.all)); end if; -- return UI.Id; return Base.UIComponent (UI).Get_Client_Id; end Get_Client_Id; -- ------------------------------ -- Renders the UIText evaluating the EL expressions it may contain. -- ------------------------------ procedure Encode_Begin (UI : in UIText; Context : in out Faces_Context'Class) is begin UI.Text.Encode_All (UI.Expr_Table, Context); end Encode_Begin; -- ------------------------------ -- Set the expression array that contains reduced expressions. -- ------------------------------ procedure Set_Expression_Table (UI : in out UIText; Expr_Table : in Views.Nodes.Expression_Access_Array_Access) is use type ASF.Views.Nodes.Expression_Access_Array_Access; begin if UI.Expr_Table /= null then raise Program_Error with "Expression table already initialized"; end if; UI.Expr_Table := Expr_Table; end Set_Expression_Table; -- ------------------------------ -- Finalize the object. -- ------------------------------ overriding procedure Finalize (UI : in out UIText) is use type ASF.Views.Nodes.Expression_Access_Array_Access; procedure Free is new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class, EL.Expressions.Expression_Access); procedure Free is new Ada.Unchecked_Deallocation (ASF.Views.Nodes.Expression_Access_Array, ASF.Views.Nodes.Expression_Access_Array_Access); begin if UI.Expr_Table /= null then for I in UI.Expr_Table'Range loop Free (UI.Expr_Table (I)); end loop; Free (UI.Expr_Table); end if; end Finalize; function Create_UIText (Tag : ASF.Views.Nodes.Text_Tag_Node_Access) return UIText_Access is Result : constant UIText_Access := new UIText; begin Result.Text := Tag; return Result; end Create_UIText; -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); end Encode_Begin; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UI.Broadcast (ASF.Lifecycles.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UI.Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UI.Broadcast (ASF.Lifecycles.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UI.Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UI.Broadcast (ASF.Lifecycles.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UI.Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UI.Broadcast (ASF.Lifecycles.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; begin -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Abstract Leaf component -- ------------------------------ overriding procedure Encode_Children (UI : in UILeaf; Context : in out Faces_Context'Class) is begin null; end Encode_Children; overriding procedure Encode_Begin (UI : in UILeaf; Context : in out Faces_Context'Class) is begin null; end Encode_Begin; overriding procedure Encode_End (UI : in UILeaf; Context : in out Faces_Context'Class) is begin null; end Encode_End; -- ------------------------------ -- Component Parameter -- ------------------------------ -- ------------------------------ -- Get the parameter name -- ------------------------------ function Get_Name (UI : UIParameter; Context : Faces_Context'Class) return String is Name : constant EL.Objects.Object := UI.Get_Attribute (Name => "name", Context => Context); begin return EL.Objects.To_String (Name); end Get_Name; -- ------------------------------ -- Get the parameter value -- ------------------------------ function Get_Value (UI : UIParameter; Context : Faces_Context'Class) return EL.Objects.Object is begin return UI.Get_Attribute (Name => "value", Context => Context); end Get_Value; -- ------------------------------ -- Get the list of parameters associated with a component. -- ------------------------------ function Get_Parameters (UI : Base.UIComponent'Class) return UIParameter_Access_Array is Result : UIParameter_Access_Array (1 .. UI.Get_Children_Count); Last : Natural := 0; procedure Collect (Child : in Base.UIComponent_Access); pragma Inline (Collect); procedure Collect (Child : in Base.UIComponent_Access) is begin if Child.all in UIParameter'Class then Last := Last + 1; Result (Last) := UIParameter (Child.all)'Access; end if; end Collect; procedure Iter is new ASF.Components.Base.Iterate (Process => Collect); pragma Inline (Iter); begin Iter (UI); return Result (1 .. Last); end Get_Parameters; end ASF.Components.Core;
----------------------------------------------------------------------- -- components-core -- ASF Core Components -- 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.Beans.Objects; with Ada.Unchecked_Deallocation; package body ASF.Components.Core is use ASF; use EL.Objects; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Return a client-side identifier for this component, generating -- one if necessary. -- ------------------------------ function Get_Client_Id (UI : UIComponentBase) return Unbounded_String is Id : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("id"); begin if Id /= null then return To_Unbounded_String (Views.Nodes.Get_Value (Id.all, UI.Get_Context.all)); end if; -- return UI.Id; return Base.UIComponent (UI).Get_Client_Id; end Get_Client_Id; -- ------------------------------ -- Renders the UIText evaluating the EL expressions it may contain. -- ------------------------------ procedure Encode_Begin (UI : in UIText; Context : in out Faces_Context'Class) is begin UI.Text.Encode_All (UI.Expr_Table, Context); end Encode_Begin; -- ------------------------------ -- Set the expression array that contains reduced expressions. -- ------------------------------ procedure Set_Expression_Table (UI : in out UIText; Expr_Table : in Views.Nodes.Expression_Access_Array_Access) is use type ASF.Views.Nodes.Expression_Access_Array_Access; begin if UI.Expr_Table /= null then raise Program_Error with "Expression table already initialized"; end if; UI.Expr_Table := Expr_Table; end Set_Expression_Table; -- ------------------------------ -- Finalize the object. -- ------------------------------ overriding procedure Finalize (UI : in out UIText) is use type ASF.Views.Nodes.Expression_Access_Array_Access; procedure Free is new Ada.Unchecked_Deallocation (EL.Expressions.Expression'Class, EL.Expressions.Expression_Access); procedure Free is new Ada.Unchecked_Deallocation (ASF.Views.Nodes.Expression_Access_Array, ASF.Views.Nodes.Expression_Access_Array_Access); begin if UI.Expr_Table /= null then for I in UI.Expr_Table'Range loop Free (UI.Expr_Table (I)); end loop; Free (UI.Expr_Table); end if; end Finalize; function Create_UIText (Tag : ASF.Views.Nodes.Text_Tag_Node_Access) return UIText_Access is Result : constant UIText_Access := new UIText; begin Result.Text := Tag; return Result; end Create_UIText; -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); end Encode_Begin; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UI.Broadcast (ASF.Lifecycles.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UI.Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UI.Broadcast (ASF.Lifecycles.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UI.Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UI.Broadcast (ASF.Lifecycles.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UI.Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UI.Broadcast (ASF.Lifecycles.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is use type Base.UIComponent_Access; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; begin -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Abstract Leaf component -- ------------------------------ overriding procedure Encode_Children (UI : in UILeaf; Context : in out Faces_Context'Class) is begin null; end Encode_Children; overriding procedure Encode_Begin (UI : in UILeaf; Context : in out Faces_Context'Class) is begin null; end Encode_Begin; overriding procedure Encode_End (UI : in UILeaf; Context : in out Faces_Context'Class) is begin null; end Encode_End; -- ------------------------------ -- Component Parameter -- ------------------------------ -- ------------------------------ -- Get the parameter name -- ------------------------------ function Get_Name (UI : UIParameter; Context : Faces_Context'Class) return String is Name : constant EL.Objects.Object := UI.Get_Attribute (Name => "name", Context => Context); begin return EL.Objects.To_String (Name); end Get_Name; -- ------------------------------ -- Get the parameter value -- ------------------------------ function Get_Value (UI : UIParameter; Context : Faces_Context'Class) return EL.Objects.Object is begin return UI.Get_Attribute (Name => "value", Context => Context); end Get_Value; -- ------------------------------ -- Get the list of parameters associated with a component. -- ------------------------------ function Get_Parameters (UI : Base.UIComponent'Class) return UIParameter_Access_Array is Result : UIParameter_Access_Array (1 .. UI.Get_Children_Count); Last : Natural := 0; procedure Collect (Child : in Base.UIComponent_Access); pragma Inline (Collect); procedure Collect (Child : in Base.UIComponent_Access) is begin if Child.all in UIParameter'Class then Last := Last + 1; Result (Last) := UIParameter (Child.all)'Access; end if; end Collect; procedure Iter is new ASF.Components.Base.Iterate (Process => Collect); pragma Inline (Iter); begin Iter (UI); return Result (1 .. Last); end Get_Parameters; end ASF.Components.Core;
Fix nesting UIView components - If the UIView is not the root component, propagate the event to the parent
Fix nesting UIView components - If the UIView is not the root component, propagate the event to the parent
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
fef9427c6748550a0721c8438f45b6eed90af1da
awa/plugins/awa-storages/src/awa-storages.ads
awa/plugins/awa-storages/src/awa-storages.ads
----------------------------------------------------------------------- -- awa-storages -- Storage 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. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Web Services. -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png] -- -- @include Storages.hbm.xml package AWA.Storages is end AWA.Storages;
----------------------------------------------------------------------- -- awa-storages -- Storage 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. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A content in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in the file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- -- Data.Set_Storage (AWA.Storages.Models.DATABASE); -- -- To save a file in the store, we can use the `Save` operation. It will read the file -- and put in in the corresponding persistent store (the database in this example). -- -- Service.Save (Data, Path); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png] -- -- @include Storages.hbm.xml package AWA.Storages is end AWA.Storages;
Document the storage service
Document the storage service
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f800a34d36239082927c4efe8c7c884914251189
src/gen-utils-gnat.adb
src/gen-utils-gnat.adb
----------------------------------------------------------------------- -- gen-utils-gnat -- GNAT utilities -- Copyright (C) 2011, 2012, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Gen.Configs; with Csets; with Snames; with Namet; with Prj.Pars; with Prj.Tree; with Prj.Env; with Prj.Util; with Makeutl; with Output; with GNAT.OS_Lib; use GNAT.OS_Lib; package body Gen.Utils.GNAT is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Utils.GNAT"); Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref; Main_Project : Prj.Project_Id; Project_Tree : constant Prj.Project_Tree_Ref := new Prj.Project_Tree_Data (Is_Root_Tree => True); -- The project tree -- ------------------------------ -- Initialize the GNAT project runtime for reading the GNAT project tree. -- Configure it according to the dynamo configuration properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is Project_Dirs : constant String := Config.Get (Gen.Configs.GEN_GNAT_PROJECT_DIRS, DEFAULT_GNAT_PROJECT_DIR); begin Log.Info ("Initializing GNAT runtime to read projects from: {0}", Project_Dirs); Project_Node_Tree := new Prj.Tree.Project_Node_Tree_Data; Prj.Tree.Initialize (Project_Node_Tree); Output.Set_Standard_Error; Csets.Initialize; Snames.Initialize; Prj.Initialize (Project_Tree); Prj.Env.Add_Directories (Makeutl.Root_Environment.Project_Path, Project_Dirs); end Initialize; -- ------------------------------ -- Read the GNAT project file identified by <b>Project_File_Name</b> and get -- in <b>Project_List</b> an ordered list of absolute project paths used by -- the root project. -- ------------------------------ procedure Read_GNAT_Project_List (Project_File_Name : in String; Project_List : out Project_Info_Vectors.Vector) is procedure Recursive_Add (Proj : in Prj.Project_Id; Tree : in Prj.Project_Tree_Ref; Dummy : in out Boolean); function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String; function Get_Project_Name (Proj : in Prj.Project_Id) return String; -- Get the variable value represented by the name <b>Name</b>. -- ??? There are probably other efficient ways to get this but I couldn't find them. function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String is use type Prj.Variable_Id; Current : Prj.Variable_Id; The_Variable : Prj.Variable; begin Current := Proj.Decl.Variables; while Current /= Prj.No_Variable loop The_Variable := Project_Tree.Shared.Variable_Elements.Table (Current); if Namet.Get_Name_String (The_Variable.Name) = Name then return Prj.Util.Value_Of (The_Variable.Value, ""); end if; Current := The_Variable.Next; end loop; return ""; end Get_Variable_Value; -- ------------------------------ -- Get the project name from the GNAT project name or from the "name" project variable. -- ------------------------------ function Get_Project_Name (Proj : in Prj.Project_Id) return String is Name : constant String := Get_Variable_Value (Proj, "name"); begin if Name'Length > 0 then return Name; else return Namet.Get_Name_String (Proj.Name); end if; end Get_Project_Name; -- ------------------------------ -- Add the full path of the GNAT project in the project list. -- ------------------------------ procedure Recursive_Add (Proj : in Prj.Project_Id; Tree : in Prj.Project_Tree_Ref; Dummy : in out Boolean) is pragma Unreferenced (Tree, Dummy); use type Prj.Project_Qualifier; Path : constant String := Namet.Get_Name_String (Proj.Path.Name); Name : constant String := Get_Project_Name (Proj); Project : Project_Info; begin Log.Info ("Using GNAT project: {0} - {1}", Path, Name); Project.Path := To_Unbounded_String (Path); Project.Name := To_Unbounded_String (Name); Project.Is_Abstract := Proj.Qualifier = Prj.Abstract_Project; Project_List.Append (Project); end Recursive_Add; procedure For_All_Projects is new Prj.For_Every_Project_Imported (Boolean, Recursive_Add); use type Prj.Project_Id; begin Log.Info ("Reading GNAT project {0}", Project_File_Name); -- Parse the GNAT project files and build the tree. Prj.Pars.Parse (Project => Main_Project, In_Tree => Project_Tree, Project_File_Name => Project_File_Name, Packages_To_Check => null, Env => Makeutl.Root_Environment, In_Node_Tree => Project_Node_Tree); if Main_Project /= Prj.No_Project then declare Dummy : Boolean := False; begin -- Scan the tree to get the list of projects (in dependency order). For_All_Projects (Main_Project, Project_Tree, Imported_First => True, With_State => Dummy); end; end if; end Read_GNAT_Project_List; end Gen.Utils.GNAT;
----------------------------------------------------------------------- -- gen-utils-gnat -- GNAT utilities -- Copyright (C) 2011, 2012, 2014, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Gen.Configs; with GPR.Snames; with GPR.Names; with GPR.Part; with GPR.Tree; with GPR.Env; with GPR.Util; with GPR.Proc; with Gpr_Build_Util; with GPR.Output; with GPR.Sdefault; with GNAT.OS_Lib; use GNAT.OS_Lib; package body Gen.Utils.GNAT is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Utils.GNAT"); Project_Node_Tree : GPR.Tree.Project_Node_Tree_Ref; Main_Project : GPR.Project_Id; Project_Node : GPR.Project_Node_Id; Project_Tree : constant GPR.Project_Tree_Ref := new GPR.Project_Tree_Data (Is_Root_Tree => True); -- ------------------------------ -- Initialize the GNAT project runtime for reading the GNAT project tree. -- Configure it according to the dynamo configuration properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is Project_Dirs : constant String := Config.Get (Gen.Configs.GEN_GNAT_PROJECT_DIRS, DEFAULT_GNAT_PROJECT_DIR); Paths : GPR.Env.Project_Search_Path; begin Log.Info ("Initializing GNAT runtime to read projects from: {0}", Project_Dirs); Project_Node_Tree := new GPR.Project_Node_Tree_Data; GPR.Tree.Initialize (Project_Node_Tree); GPR.Output.Set_Standard_Error; GPR.Snames.Initialize; GPR.Initialize (Project_Tree); GPR.Env.Initialize_Default_Project_Path (Gpr_Build_Util.Root_Environment.Project_Path, GPR.Sdefault.Hostname); GPR.Env.Add_Directories (Gpr_Build_Util.Root_Environment.Project_Path, Project_Dirs); Paths := Gpr_Build_Util.Root_Environment.Project_Path; Log.Info ("Added directories {0}", Gpr.Util.Executable_Prefix_Path); end Initialize; -- ------------------------------ -- Read the GNAT project file identified by <b>Project_File_Name</b> and get -- in <b>Project_List</b> an ordered list of absolute project paths used by -- the root project. -- ------------------------------ procedure Read_GNAT_Project_List (Project_File_Name : in String; Project_List : out Project_Info_Vectors.Vector) is procedure Recursive_Add (Proj : in GPR.Project_Id; Tree : in GPR.Project_Tree_Ref; Dummy : in out Boolean); function Get_Variable_Value (Proj : in GPR.Project_Id; Name : in String) return String; function Get_Project_Name (Proj : in GPR.Project_Id) return String; -- Get the variable value represented by the name <b>Name</b>. -- ??? There are probably other efficient ways to get this but I couldn't find them. function Get_Variable_Value (Proj : in GPR.Project_Id; Name : in String) return String is use type GPR.Variable_Id; Current : GPR.Variable_Id; The_Variable : GPR.Variable; begin Current := Proj.Decl.Variables; while Current /= GPR.No_Variable loop The_Variable := Project_Tree.Shared.Variable_Elements.Table (Current); if GPR.Names.Get_Name_String (The_Variable.Name) = Name then return GPR.Util.Value_Of (The_Variable.Value, ""); end if; Current := The_Variable.Next; end loop; return ""; end Get_Variable_Value; -- ------------------------------ -- Get the project name from the GNAT project name or from the "name" project variable. -- ------------------------------ function Get_Project_Name (Proj : in GPR.Project_Id) return String is Name : constant String := Get_Variable_Value (Proj, "name"); begin if Name'Length > 0 then return Name; else return GPR.Names.Get_Name_String (Proj.Name); end if; end Get_Project_Name; -- ------------------------------ -- Add the full path of the GNAT project in the project list. -- ------------------------------ procedure Recursive_Add (Proj : in GPR.Project_Id; Tree : in GPR.Project_Tree_Ref; Dummy : in out Boolean) is pragma Unreferenced (Tree, Dummy); use type GPR.Project_Qualifier; Path : constant String := GPR.Names.Get_Name_String (Proj.Path.Name); Name : constant String := Get_Project_Name (Proj); Project : Project_Info; begin Log.Info ("Using GNAT project: {0} - {1}", Path, Name); Project.Path := To_Unbounded_String (Path); Project.Name := To_Unbounded_String (Name); Project.Is_Abstract := Proj.Qualifier = GPR.Abstract_Project; Project_List.Append (Project); end Recursive_Add; procedure For_All_Projects is new GPR.For_Every_Project_Imported (Boolean, Recursive_Add); begin Log.Info ("Reading GNAT project {0}", Project_File_Name); -- Parse the GNAT project files and build the tree. GPR.Part.Parse (Project => Project_Node, In_Tree => Project_Node_Tree, Project_File_Name => Project_File_Name, Packages_To_Check => null, Is_Config_File => False, Env => Gpr_Build_Util.Root_Environment); if not GPR.Tree.No (Project_Node) then declare Dummy : Boolean := False; Success : Boolean; begin GPR.Proc.Process_Project_Tree_Phase_1 (In_Tree => Project_Tree, Project => Main_Project, Packages_To_Check => null, From_Project_Node => Project_Node, From_Project_Node_Tree => Project_Node_Tree, Env => Gpr_Build_Util.Root_Environment, Reset_Tree => True, Success => Success, On_New_Tree_Loaded => null); -- Scan the tree to get the list of projects (in dependency order). For_All_Projects (Main_Project, Project_Tree, Imported_First => True, With_State => Dummy); end; end if; end Read_GNAT_Project_List; end Gen.Utils.GNAT;
Update to use the GPR library instead of the src/gnat files that were imported from the GNU gcc compiler
Update to use the GPR library instead of the src/gnat files that were imported from the GNU gcc compiler
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2a776e7f2a849dfdffd7286c8afb5ca637fe5395
src/http/util-http-clients-mockups.adb
src/http/util-http-clients-mockups.adb
----------------------------------------------------------------------- -- util-http-clients-mockups -- HTTP Clients -- 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.Files; with Util.Http.Mockups; package body Util.Http.Clients.Mockups is use Ada.Strings.Unbounded; Manager : aliased File_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Set the path of the file that contains the response for the next -- <b>Do_Get</b> and <b>Do_Post</b> calls. -- ------------------------------ procedure Set_File (Path : in String) is begin Manager.File := To_Unbounded_String (Path); end Set_File; procedure Create (Manager : in File_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new Util.Http.Mockups.Mockup_Request; end Create; overriding procedure Do_Get (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Http, URI); Rep : constant Util.Http.Mockups.Mockup_Response_Access := new Util.Http.Mockups.Mockup_Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Delegate := Rep.all'Access; Util.Files.Read_File (Path => To_String (Manager.File), Into => Content, Max_Size => 100000); Rep.Set_Body (To_String (Content)); Rep.Set_Status (SC_OK); end Do_Get; overriding procedure Do_Post (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Data); begin Manager.Do_Get (Http, URI, Reply); end Do_Post; overriding procedure Do_Put (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Data); begin Manager.Do_Get (Http, URI, Reply); end Do_Put; end Util.Http.Clients.Mockups;
----------------------------------------------------------------------- -- util-http-clients-mockups -- HTTP Clients -- 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.Files; with Util.Http.Mockups; package body Util.Http.Clients.Mockups is use Ada.Strings.Unbounded; Manager : aliased File_Http_Manager; -- ------------------------------ -- Register the Http manager. -- ------------------------------ procedure Register is begin Default_Http_Manager := Manager'Access; end Register; -- ------------------------------ -- Set the path of the file that contains the response for the next -- <b>Do_Get</b> and <b>Do_Post</b> calls. -- ------------------------------ procedure Set_File (Path : in String) is begin Manager.File := To_Unbounded_String (Path); end Set_File; procedure Create (Manager : in File_Http_Manager; Http : in out Client'Class) is pragma Unreferenced (Manager); begin Http.Delegate := new Util.Http.Mockups.Mockup_Request; end Create; overriding procedure Do_Get (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Reply : out Response'Class) is pragma Unreferenced (Http, URI); Rep : constant Util.Http.Mockups.Mockup_Response_Access := new Util.Http.Mockups.Mockup_Response; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Delegate := Rep.all'Access; Util.Files.Read_File (Path => To_String (Manager.File), Into => Content, Max_Size => 100000); Rep.Set_Body (To_String (Content)); Rep.Set_Status (SC_OK); end Do_Get; overriding procedure Do_Post (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Data); begin Manager.Do_Get (Http, URI, Reply); end Do_Post; overriding procedure Do_Put (Manager : in File_Http_Manager; Http : in Client'Class; URI : in String; Data : in String; Reply : out Response'Class) is pragma Unreferenced (Data); begin Manager.Do_Get (Http, URI, Reply); end Do_Put; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ overriding procedure Set_Timeout (Manager : in File_Http_Manager; Http : in Client'Class; Timeout : in Duration) is pragma Unreferenced (Manager, Http, Timeout); begin null; end Set_Timeout; end Util.Http.Clients.Mockups;
Implement the Set_Timeout procedure
Implement the Set_Timeout procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c943417e2d8d6f16ae78c4f3e0d5a41c0ea960ef
src/natools-web-fallback_render.adb
src/natools-web-fallback_render.adb
------------------------------------------------------------------------------ -- Copyright (c) 2015-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 Ada.Calendar; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Conditionals.Strings; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Fallback_Render; with Natools.Web.ACL; with Natools.Web.Comment_Cookies; with Natools.Web.Escapes; with Natools.Web.Filters.Stores; with Natools.Web.Tags; with Natools.Web.String_Tables; procedure Natools.Web.Fallback_Render (Exchange : in out Natools.Web.Sites.Exchange; Name : in Natools.S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class; Context : in String := ""; Re_Enter : access procedure (Exchange : in out Natools.Web.Sites.Exchange; Expression : in out Natools.S_Expressions.Lockable.Descriptor'Class) := null; Elements : in Natools.Web.Containers.Expression_Maps.Constant_Map := Natools.Web.Containers.Expression_Maps.Empty_Constant_Map; Severity : in Severities.Code := Severities.Error) is package Commands renames Natools.Static_Maps.Web.Fallback_Render; use type S_Expressions.Events.Event; procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference); procedure Report_Unknown_Command; procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference) is begin if not Ref.Is_Empty then Escapes.Write (Exchange, S_Expressions.To_String (Ref.Query), Escapes.HTML_Attribute); elsif Re_Enter /= null then Re_Enter (Exchange, Arguments); end if; end Render_Ref; procedure Report_Unknown_Command is begin if Context /= "" then Log (Severity, "Unknown render command """ & S_Expressions.To_String (Name) & """ in " & Context); end if; end Report_Unknown_Command; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown => Report_Unknown_Command; when Commands.Current_Time => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Ada.Calendar.Clock); when Commands.Cookies => String_Tables.Render (Exchange, String_Tables.Create (Exchange.Cookie_Table), Arguments); when Commands.Comment_Cookie_Filter => Render_Ref (Comment_Cookies.Filter (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Link => Render_Ref (Comment_Cookies.Link (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Mail => Render_Ref (Comment_Cookies.Mail (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Name => Render_Ref (Comment_Cookies.Name (Sites.Comment_Info (Exchange))); when Commands.Element => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Template => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.Element_Or_Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments); begin Re_Enter (Exchange, Template); end; end if; when Commands.Filter => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then begin declare Filter : Filters.Filter'Class := Exchange.Site.Get_Filter (Arguments.Current_Atom); begin Arguments.Next; Exchange.Insert_Filter (Filter); Re_Enter (Exchange, Arguments); Exchange.Remove_Filter (Filter); end; exception when Filters.Stores.No_Filter => null; end; end if; when Commands.If_Comment_Cookie_Filter_Is => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare use type S_Expressions.Atom; Ref : constant S_Expressions.Atom_Refs.Immutable_Reference := Comment_Cookies.Filter (Sites.Comment_Info (Exchange)); begin if not Ref.Is_Empty and then Ref.Query = Arguments.Current_Atom then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.If_Has_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Has_Not_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Header_Else => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Open_List then declare Lock : S_Expressions.Lockable.Lock_State; Event : S_Expressions.Events.Event; Condition : Boolean; begin Arguments.Next (Event); if Event /= S_Expressions.Events.Add_Atom then return; end if; Arguments.Lock (Lock); Evaluate_Condition : declare Value : constant String := Exchange.Header (S_Expressions.To_String (Arguments.Current_Atom)); begin Arguments.Next; Condition := S_Expressions.Conditionals.Strings.Evaluate (Value, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end Evaluate_Condition; Arguments.Next (Event); case Event is when S_Expressions.Events.Add_Atom => if Condition then Exchange.Append (Arguments.Current_Atom); end if; when S_Expressions.Events.Open_List => if Condition then Arguments.Lock (Lock); begin Arguments.Next; Re_Enter (Exchange, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end; else Arguments.Close_Current_List; end if; when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => return; end case; if Condition then return; end if; Arguments.Next (Event); case Event is when S_Expressions.Events.Add_Atom => Exchange.Append (Arguments.Current_Atom); when S_Expressions.Events.Open_List => Arguments.Lock (Lock); begin Arguments.Next; Re_Enter (Exchange, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end; when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => return; end case; end; end if; when Commands.If_Parameter_Is => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Param_Value : constant String := Exchange.Parameter (S_Expressions.To_String (Arguments.Current_Atom)); Event : S_Expressions.Events.Event; begin Arguments.Next (Event); if Event = S_Expressions.Events.Add_Atom and then Param_Value = S_Expressions.To_String (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Load_Date => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Exchange.Site.Load_Date); when Commands.Optional_Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Optional => True); when Commands.Parameter => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Parameter_Name : constant String := S_Expressions.To_String (Arguments.Current_Atom); begin if Exchange.Has_Parameter (Parameter_Name) then Escapes.Write (Exchange, Exchange.Parameter (Parameter_Name), Escapes.HTML_Attribute); elsif Re_Enter /= null then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Set_MIME_Type => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Exchange.Set_MIME_Type (Arguments.Current_Atom); end if; when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments); when Commands.Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Element => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.User => if Re_Enter = null then Report_Unknown_Command; else declare Match : Boolean := False; begin ACL.Match (Sites.Identity (Exchange), Arguments, Match); if Match then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; end case; end Natools.Web.Fallback_Render;
------------------------------------------------------------------------------ -- Copyright (c) 2015-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 Ada.Calendar; with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Caches; with Natools.S_Expressions.Conditionals.Strings; with Natools.S_Expressions.Lockable; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Fallback_Render; with Natools.Web.ACL; with Natools.Web.Comment_Cookies; with Natools.Web.Escapes; with Natools.Web.Filters.Stores; with Natools.Web.Tags; with Natools.Web.String_Tables; procedure Natools.Web.Fallback_Render (Exchange : in out Natools.Web.Sites.Exchange; Name : in Natools.S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class; Context : in String := ""; Re_Enter : access procedure (Exchange : in out Natools.Web.Sites.Exchange; Expression : in out Natools.S_Expressions.Lockable.Descriptor'Class) := null; Elements : in Natools.Web.Containers.Expression_Maps.Constant_Map := Natools.Web.Containers.Expression_Maps.Empty_Constant_Map; Severity : in Severities.Code := Severities.Error) is package Commands renames Natools.Static_Maps.Web.Fallback_Render; use type S_Expressions.Events.Event; procedure Render_Then_Else (Condition : in Boolean); procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference); procedure Report_Unknown_Command; procedure Render_Then_Else (Condition : in Boolean) is Lock : S_Expressions.Lockable.Lock_State; Event : S_Expressions.Events.Event; begin Arguments.Next (Event); case Event is when S_Expressions.Events.Add_Atom => if Condition then Exchange.Append (Arguments.Current_Atom); end if; when S_Expressions.Events.Open_List => if Condition then Arguments.Lock (Lock); begin Arguments.Next; Re_Enter (Exchange, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end; else Arguments.Close_Current_List; end if; when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => return; end case; if Condition then return; end if; Arguments.Next (Event); case Event is when S_Expressions.Events.Add_Atom => Exchange.Append (Arguments.Current_Atom); when S_Expressions.Events.Open_List => Arguments.Lock (Lock); begin Arguments.Next; Re_Enter (Exchange, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end; when S_Expressions.Events.Close_List | S_Expressions.Events.End_Of_Input | S_Expressions.Events.Error => return; end case; end Render_Then_Else; procedure Render_Ref (Ref : in S_Expressions.Atom_Refs.Immutable_Reference) is begin if not Ref.Is_Empty then Escapes.Write (Exchange, S_Expressions.To_String (Ref.Query), Escapes.HTML_Attribute); elsif Re_Enter /= null then Re_Enter (Exchange, Arguments); end if; end Render_Ref; procedure Report_Unknown_Command is begin if Context /= "" then Log (Severity, "Unknown render command """ & S_Expressions.To_String (Name) & """ in " & Context); end if; end Report_Unknown_Command; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown => Report_Unknown_Command; when Commands.Current_Time => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Ada.Calendar.Clock); when Commands.Cookies => String_Tables.Render (Exchange, String_Tables.Create (Exchange.Cookie_Table), Arguments); when Commands.Comment_Cookie_Filter => Render_Ref (Comment_Cookies.Filter (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Link => Render_Ref (Comment_Cookies.Link (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Mail => Render_Ref (Comment_Cookies.Mail (Sites.Comment_Info (Exchange))); when Commands.Comment_Cookie_Name => Render_Ref (Comment_Cookies.Name (Sites.Comment_Info (Exchange))); when Commands.Element => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Template => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.Element_Or_Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments); begin Re_Enter (Exchange, Template); end; end if; when Commands.Filter => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then begin declare Filter : Filters.Filter'Class := Exchange.Site.Get_Filter (Arguments.Current_Atom); begin Arguments.Next; Exchange.Insert_Filter (Filter); Re_Enter (Exchange, Arguments); Exchange.Remove_Filter (Filter); end; exception when Filters.Stores.No_Filter => null; end; end if; when Commands.If_Comment_Cookie_Filter_Is => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare use type S_Expressions.Atom; Ref : constant S_Expressions.Atom_Refs.Immutable_Reference := Comment_Cookies.Filter (Sites.Comment_Info (Exchange)); begin if not Ref.Is_Empty and then Ref.Query = Arguments.Current_Atom then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.If_Has_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Has_Not_Element => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Elements.Contains (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; when Commands.If_Header_Else => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Open_List then declare Lock : S_Expressions.Lockable.Lock_State; Event : S_Expressions.Events.Event; Condition : Boolean; begin Arguments.Next (Event); if Event /= S_Expressions.Events.Add_Atom then return; end if; Arguments.Lock (Lock); Evaluate_Condition : declare Value : constant String := Exchange.Header (S_Expressions.To_String (Arguments.Current_Atom)); begin Arguments.Next; Condition := S_Expressions.Conditionals.Strings.Evaluate (Value, Arguments); Arguments.Unlock (Lock); exception when others => Arguments.Unlock (Lock, False); raise; end Evaluate_Condition; Render_Then_Else (Condition); end; end if; when Commands.If_Parameter_Is => if Re_Enter = null then Report_Unknown_Command; elsif Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Param_Value : constant String := Exchange.Parameter (S_Expressions.To_String (Arguments.Current_Atom)); Event : S_Expressions.Events.Event; begin Arguments.Next (Event); if Event = S_Expressions.Events.Add_Atom and then Param_Value = S_Expressions.To_String (Arguments.Current_Atom) then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Load_Date => S_Expressions.Templates.Dates.Render (Exchange, Arguments, Exchange.Site.Load_Date); when Commands.Optional_Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Optional => True); when Commands.Parameter => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Parameter_Name : constant String := S_Expressions.To_String (Arguments.Current_Atom); begin if Exchange.Has_Parameter (Parameter_Name) then Escapes.Write (Exchange, Exchange.Parameter (Parameter_Name), Escapes.HTML_Attribute); elsif Re_Enter /= null then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; when Commands.Set_MIME_Type => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Exchange.Set_MIME_Type (Arguments.Current_Atom); end if; when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments); when Commands.Template => if Re_Enter = null then Report_Unknown_Command; else declare Template : S_Expressions.Caches.Cursor := Exchange.Site.Get_Template (Elements, Arguments, Lookup_Element => False); begin Re_Enter (Exchange, Template); end; end if; when Commands.User => if Re_Enter = null then Report_Unknown_Command; else declare Match : Boolean := False; begin ACL.Match (Sites.Identity (Exchange), Arguments, Match); if Match then Arguments.Next; Re_Enter (Exchange, Arguments); end if; end; end if; end case; end Natools.Web.Fallback_Render;
refactor the then/else render in a dedicated procedure
fallback_render: refactor the then/else render in a dedicated procedure
Ada
isc
faelys/natools-web,faelys/natools-web
e59c9653a294e50c290a72cbcbba02f879f76053
ARM/STMicro/STM32/drivers/ltdc/stm32-ltdc.adb
ARM/STMicro/STM32/drivers/ltdc/stm32-ltdc.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f429i_discovery_lcd.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief This file includes the LTDC driver to control LCD display. -- -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ with Ada.Unchecked_Conversion; with Ada.Real_Time; use Ada.Real_Time; with STM32_SVD.LTDC; use STM32_SVD.LTDC; with STM32_SVD.RCC; use STM32_SVD.RCC; with STM32.SDRAM; use STM32.SDRAM; package body STM32.LTDC is Frame_Buffer_Array : array (LCD_Layer) of Frame_Buffer_Access; Current_Pixel_Fmt : Pixel_Format := Pixel_Fmt_ARGB1555; Swap_X_Y : Boolean := False; type FB32 is array (Natural range 0 .. LCD_Height - 1, Natural range 0 .. LCD_Width - 1) of Word with Component_Size => 32, Volatile; type Swap_FB32 is array (Natural range 0 .. LCD_Width - 1, Natural range 0 .. LCD_Height - 1) of Word with Component_Size => 32, Volatile; type FB24 is array (Natural range 0 .. LCD_Height - 1, Natural range 0 .. (LCD_Width * 3) - 1) of Byte with Component_Size => 8, Volatile; type Swap_FB24 is array (Natural range 0 .. LCD_Width - 1, Natural range 0 .. LCD_Height * 3 - 1) of Byte with Component_Size => 8, Volatile; type FB16 is array (Natural range 0 .. LCD_Height - 1, Natural range 0 .. LCD_Width - 1) of Short with Component_Size => 16, Volatile; type Swap_FB16 is array (Natural range 0 .. LCD_Width - 1, Natural range 0 .. LCD_Height - 1) of Short with Component_Size => 16, Volatile; type Frame_Buffer (Pixel_Fmt : Pixel_Format; Swap : Boolean) is record case Swap is when False => case Pixel_Fmt is when Pixel_Fmt_ARGB8888 => Arr32 : FB32; when Pixel_Fmt_RGB888 => Arr24 : FB24; when others => Arr16 : FB16; end case; when True => case Pixel_Fmt is when Pixel_Fmt_ARGB8888 => SwArr32 : Swap_FB32; when Pixel_Fmt_RGB888 => SwArr24 : Swap_FB24; when others => SwArr16 : Swap_FB16; end case; end case; end record with Unchecked_Union, Volatile; type Frame_Buffer_Int_Access is access all Frame_Buffer; function Pixel_Size (Fmt : Pixel_Format) return Positive; ---------- -- Init -- ---------- package Init is BF1_Constant_Alpha : constant := 2#100#; BF2_Constant_Alpha : constant := 2#101#; BF1_Pixel_Alpha : constant := 2#110#; BF2_Pixel_Alpha : constant := 2#111#; procedure Reload_Config (Immediate : Boolean); procedure Set_Layer_CFBA (Layer : LCD_Layer; FBA : Frame_Buffer_Access); -- Sets the frame buffer of the specified layer function Get_Layer_CFBA (Layer : LCD_Layer) return Frame_Buffer_Access; -- Gets the frame buffer of the specified layer procedure LTDC_Init; procedure Layer_Init (Layer : LCD_Layer; Config : Pixel_Format; BF1, BF2 : UInt3); procedure Set_Layer_State (Layer : LCD_Layer; State : Boolean); -- Enables/Disables the specified layer end Init; package body Init is separate; ------------------- -- Reload_Config -- ------------------- procedure Reload_Config (Immediate : Boolean := True) renames Init.Reload_Config; --------------------- -- Set_Layer_State -- --------------------- procedure Set_Layer_State (Layer : LCD_Layer; State : Layer_State) is begin Init.Set_Layer_State (Layer, State = Enabled); end Set_Layer_State; ---------------- -- Initialize -- ---------------- procedure Initialize (Pixel_Fmt : Pixel_Format := Pixel_Fmt_ARGB1555) is FB_Size : constant Word := Word (LCD_Width * LCD_Height * Pixel_Size (Pixel_Fmt)); begin if Initialized then return; end if; Pre_LTDC_Initialize; delay until Clock + Milliseconds (200); Init.LTDC_Init; STM32.SDRAM.Initialize; Current_Pixel_Fmt := Pixel_Fmt; Frame_Buffer_Array (Layer1) := STM32.SDRAM.Reserve (FB_Size); Init.Layer_Init (Layer1, Pixel_Fmt, Init.BF1_Constant_Alpha, Init.BF2_Constant_Alpha); Init.Layer_Init (Layer2, Pixel_Fmt, Init.BF1_Pixel_Alpha, Init.BF2_Pixel_Alpha); Init.Set_Layer_State (Layer1, True); Init.Set_Layer_State (Layer2, False); Reload_Config (True); -- enable Dither LTDC_Periph.GCR.DEN := 1; Reload_Config (True); Post_LTDC_Initialize; end Initialize; ----------------- -- Initialized -- ----------------- function Initialized return Boolean is begin return Frame_Buffer_Array (Layer1) /= Null_Address; end Initialized; ---------------- -- Pixel_Size -- ---------------- function Pixel_Size (Fmt : Pixel_Format) return Positive is (case Fmt is when Pixel_Fmt_ARGB8888 => 4, when Pixel_Fmt_RGB888 => 3, when Pixel_Fmt_RGB565 | Pixel_Fmt_ARGB1555 | Pixel_Fmt_ARGB4444 => 2); ------------------- -- Get_Pixel_Fmt -- ------------------- function Get_Pixel_Fmt return Pixel_Format is (Current_Pixel_Fmt); -------------------------- -- Current_Frame_Buffer -- -------------------------- function Current_Frame_Buffer (Layer : LCD_Layer) return Frame_Buffer_Access renames Init.Get_Layer_CFBA; ---------------------- -- Set_Frame_Buffer -- ---------------------- procedure Set_Frame_Buffer (Layer : LCD_Layer; Addr : Frame_Buffer_Access) renames Init.Set_Layer_CFBA; --------------------- -- Set_Orientation -- --------------------- procedure Set_Orientation (Orientation : Orientation_Mode) is begin case Orientation is when Portrait => Swap_X_Y := LCD_Width > LCD_Height; when Landscape => Swap_X_Y := LCD_Height > LCD_Width; end case; end Set_Orientation; --------------------- -- Get_Orientation -- --------------------- function Get_Orientation return Orientation_Mode is begin return (if Pixel_Width > Pixel_Height then Landscape else Portrait); end Get_Orientation; ------------ -- SwapXY -- ------------ function SwapXY return Boolean is (Swap_X_Y); ----------------- -- Pixel_Width -- ----------------- function Pixel_Width return Natural is (if Swap_X_Y then LCD_Height else LCD_Width); ------------------ -- Pixel_Height -- ------------------ function Pixel_Height return Natural is (if Swap_X_Y then LCD_Width else LCD_Height); -------------------- -- Set_Background -- -------------------- procedure Set_Background (R, G, B : Byte) is begin LTDC_Periph.BCCR.BC := UInt24 (R * 2 ** 16) or UInt24 (G * 2 ** 8) or UInt24 (B); end Set_Background; --------------- -- Set_Pixel -- --------------- procedure Set_Pixel (Layer : LCD_Layer; X : Natural; Y : Natural; Value : Word) is function To_FB_Access is new Ada.Unchecked_Conversion (System.Address, Frame_Buffer_Int_Access); Buff : constant Frame_Buffer_Int_Access := To_FB_Access (Frame_Buffer_Array (Layer)); begin if Y >= Pixel_Height or else X >= Pixel_Width then return; end if; if not Swap_X_Y then Buff.Arr32 (Y, X) := Value; else Buff.SwArr32 (X, Y) := Value; end if; end Set_Pixel; --------------- -- Set_Pixel -- --------------- procedure Set_Pixel (Layer : LCD_Layer; X : Natural; Y : Natural; Value : UInt24) is function To_FB_Access is new Ada.Unchecked_Conversion (System.Address, Frame_Buffer_Int_Access); Buff : constant Frame_Buffer_Int_Access := To_FB_Access (Frame_Buffer_Array (Layer)); begin if Y >= Pixel_Height or else X >= Pixel_Width then return; end if; if not Swap_X_Y then -- Red: Buff.Arr24 (Y, (X * 3) + 2) := Byte (Value and 16#FF#); -- Green: Buff.Arr24 (Y, (X * 3) + 1) := Byte ((Value and 16#FF00#) / (2 ** 8)); -- Blue: Buff.Arr24 (Y, (X * 3) + 0) := Byte ((Value and 16#FF0000#) / (2 ** 16)); else -- Red: Buff.SwArr24 (X, (Y * 3) + 2) := Byte (Value and 16#FF#); -- Green: Buff.SwArr24 (X, (Y * 3) + 1) := Byte ((Value and 16#FF00#) / (2 ** 8)); -- Blue: Buff.SwArr24 (X, (Y * 3) + 0) := Byte ((Value and 16#FF0000#) / (2 ** 16)); end if; end Set_Pixel; --------------- -- Set_Pixel -- --------------- procedure Set_Pixel (Layer : LCD_Layer; X : Natural; Y : Natural; Value : Half_Word) is function To_FB_Access is new Ada.Unchecked_Conversion (System.Address, Frame_Buffer_Int_Access); Buff : constant Frame_Buffer_Int_Access := To_FB_Access (Frame_Buffer_Array (Layer)); begin if Y >= Pixel_Height or else X >= Pixel_Width then return; end if; if not Swap_X_Y then Buff.Arr16 (Y, X) := Value; else Buff.SwArr16 (X, Y) := Value; end if; end Set_Pixel; ----------------- -- Pixel_Value -- ----------------- function Pixel_Value (Layer : LCD_Layer; X : Natural; Y : Natural) return Word is function To_FB_Access is new Ada.Unchecked_Conversion (System.Address, Frame_Buffer_Int_Access); Buff : constant Frame_Buffer_Int_Access := To_FB_Access (Frame_Buffer_Array (Layer)); begin if not Swap_X_Y then return Buff.Arr32 (Y, X); else return Buff.SwArr32 (X, Y); end if; end Pixel_Value; ----------------- -- Pixel_Value -- ----------------- function Pixel_Value (Layer : LCD_Layer; X : Natural; Y : Natural) return UInt24 is function To_FB_Access is new Ada.Unchecked_Conversion (System.Address, Frame_Buffer_Int_Access); Buff : constant Frame_Buffer_Int_Access := To_FB_Access (Frame_Buffer_Array (Layer)); Ret : UInt24; begin if not Swap_X_Y then Ret := UInt24 (Buff.Arr24 (Y, X * 3 + 2)) or UInt24 (Buff.Arr24 (Y, X * 3 + 1)) * 2 ** 8 or UInt24 (Buff.Arr24 (Y, X * 3 + 0)) * 2 ** 16; else Ret := UInt24 (Buff.SwArr24 (X, Y * 3 + 2)) or UInt24 (Buff.SwArr24 (X, Y * 3 + 1)) * 2 ** 8 or UInt24 (Buff.SwArr24 (X, Y * 3 + 0)) * 2 ** 16; end if; return Ret; end Pixel_Value; ----------------- -- Pixel_Value -- ----------------- function Pixel_Value (Layer : LCD_Layer; X : Natural; Y : Natural) return Half_Word is function To_FB_Access is new Ada.Unchecked_Conversion (System.Address, Frame_Buffer_Int_Access); Buff : constant Frame_Buffer_Int_Access := To_FB_Access (Frame_Buffer_Array (Layer)); begin if not Swap_X_Y then return Buff.Arr16 (Y, X); else return Buff.SwArr16 (X, Y); end if; end Pixel_Value; end STM32.LTDC;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- -- -- -- This file is based on: -- -- -- -- @file stm32f429i_discovery_lcd.c -- -- @author MCD Application Team -- -- @version V1.1.0 -- -- @date 19-June-2014 -- -- @brief This file includes the LTDC driver to control LCD display. -- -- -- -- -- COPYRIGHT(c) 2014 STMicroelectronics -- ------------------------------------------------------------------------------ with Ada.Unchecked_Conversion; with Ada.Real_Time; use Ada.Real_Time; with STM32_SVD.LTDC; use STM32_SVD.LTDC; with STM32_SVD.RCC; use STM32_SVD.RCC; with STM32.SDRAM; use STM32.SDRAM; package body STM32.LTDC is Frame_Buffer_Array : array (LCD_Layer) of Frame_Buffer_Access; Current_Pixel_Fmt : Pixel_Format := Pixel_Fmt_ARGB1555; Swap_X_Y : Boolean := False; subtype LCD_Height_Range is Natural range 0 .. LCD_Height - 1; subtype LCD_Width_Range is Natural range 0 .. LCD_Width - 1; type FB32 is array (LCD_Height_Range, LCD_Width_Range) of Word with Component_Size => 32, Volatile; type FB24 is array (LCD_Height_Range, 0 .. LCD_Height * 3 - 1) of Byte with Component_Size => 8, Volatile; type FB16 is array (LCD_Height_Range, LCD_Width_Range) of Short with Component_Size => 16, Volatile; function Pixel_Size (Fmt : Pixel_Format) return Positive; ---------- -- Init -- ---------- package Init is BF1_Constant_Alpha : constant := 2#100#; BF2_Constant_Alpha : constant := 2#101#; BF1_Pixel_Alpha : constant := 2#110#; BF2_Pixel_Alpha : constant := 2#111#; procedure Reload_Config (Immediate : Boolean); procedure Set_Layer_CFBA (Layer : LCD_Layer; FBA : Frame_Buffer_Access); -- Sets the frame buffer of the specified layer function Get_Layer_CFBA (Layer : LCD_Layer) return Frame_Buffer_Access; -- Gets the frame buffer of the specified layer procedure LTDC_Init; procedure Layer_Init (Layer : LCD_Layer; Config : Pixel_Format; BF1, BF2 : UInt3); procedure Set_Layer_State (Layer : LCD_Layer; State : Boolean); -- Enables/Disables the specified layer end Init; package body Init is separate; ------------------- -- Reload_Config -- ------------------- procedure Reload_Config (Immediate : Boolean := True) renames Init.Reload_Config; --------------------- -- Set_Layer_State -- --------------------- procedure Set_Layer_State (Layer : LCD_Layer; State : Layer_State) is begin Init.Set_Layer_State (Layer, State = Enabled); end Set_Layer_State; ---------------- -- Initialize -- ---------------- procedure Initialize (Pixel_Fmt : Pixel_Format := Pixel_Fmt_ARGB1555) is FB_Size : constant Word := Word (LCD_Width * LCD_Height * Pixel_Size (Pixel_Fmt)); begin if Initialized then return; end if; Pre_LTDC_Initialize; delay until Clock + Milliseconds (200); Init.LTDC_Init; STM32.SDRAM.Initialize; Current_Pixel_Fmt := Pixel_Fmt; Frame_Buffer_Array (Layer1) := STM32.SDRAM.Reserve (FB_Size); Init.Layer_Init (Layer1, Pixel_Fmt, Init.BF1_Constant_Alpha, Init.BF2_Constant_Alpha); Init.Layer_Init (Layer2, Pixel_Fmt, Init.BF1_Pixel_Alpha, Init.BF2_Pixel_Alpha); Init.Set_Layer_State (Layer1, True); Init.Set_Layer_State (Layer2, False); Reload_Config (True); -- enable Dither LTDC_Periph.GCR.DEN := 1; Reload_Config (True); Post_LTDC_Initialize; end Initialize; ----------------- -- Initialized -- ----------------- function Initialized return Boolean is begin return Frame_Buffer_Array (Layer1) /= Null_Address; end Initialized; ---------------- -- Pixel_Size -- ---------------- function Pixel_Size (Fmt : Pixel_Format) return Positive is (case Fmt is when Pixel_Fmt_ARGB8888 => 4, when Pixel_Fmt_RGB888 => 3, when Pixel_Fmt_RGB565 | Pixel_Fmt_ARGB1555 | Pixel_Fmt_ARGB4444 => 2); ------------------- -- Get_Pixel_Fmt -- ------------------- function Get_Pixel_Fmt return Pixel_Format is (Current_Pixel_Fmt); -------------------------- -- Current_Frame_Buffer -- -------------------------- function Current_Frame_Buffer (Layer : LCD_Layer) return Frame_Buffer_Access renames Init.Get_Layer_CFBA; ---------------------- -- Set_Frame_Buffer -- ---------------------- procedure Set_Frame_Buffer (Layer : LCD_Layer; Addr : Frame_Buffer_Access) renames Init.Set_Layer_CFBA; --------------------- -- Set_Orientation -- --------------------- procedure Set_Orientation (Orientation : Orientation_Mode) is begin case Orientation is when Portrait => Swap_X_Y := LCD_Width > LCD_Height; when Landscape => Swap_X_Y := LCD_Height > LCD_Width; end case; end Set_Orientation; --------------------- -- Get_Orientation -- --------------------- function Get_Orientation return Orientation_Mode is begin return (if Pixel_Width > Pixel_Height then Landscape else Portrait); end Get_Orientation; ------------ -- SwapXY -- ------------ function SwapXY return Boolean is (Swap_X_Y); ----------------- -- Pixel_Width -- ----------------- function Pixel_Width return Natural is (if Swap_X_Y then LCD_Height else LCD_Width); ------------------ -- Pixel_Height -- ------------------ function Pixel_Height return Natural is (if Swap_X_Y then LCD_Width else LCD_Height); -------------------- -- Set_Background -- -------------------- procedure Set_Background (R, G, B : Byte) is begin LTDC_Periph.BCCR.BC := UInt24 (R * 2 ** 16) or UInt24 (G * 2 ** 8) or UInt24 (B); end Set_Background; procedure Convert (X, Y : Natural; Ok : out Boolean; X0 : out LCD_Width_Range; Y0 : out LCD_Height_Range) is begin if Y >= Pixel_Height or else X >= Pixel_Width then Ok := False; else Ok := True; if not Swap_X_Y then Y0 := Y; X0 := X; else Y0 := LCD_Height - 1 - X; X0 := Y; end if; end if; end Convert; --------------- -- Set_Pixel -- --------------- procedure Set_Pixel (Layer : LCD_Layer; X : Natural; Y : Natural; Value : Word) is FB : FB32 with Import, Address => Frame_Buffer_Array (Layer); X0 : LCD_Height_Range; Y0 : LCD_Width_Range; Ok : Boolean; begin Convert (X, Y, Ok, X0, Y0); if Ok then FB (Y0, X0) := Value; end if; end Set_Pixel; --------------- -- Set_Pixel -- --------------- procedure Set_Pixel (Layer : LCD_Layer; X : Natural; Y : Natural; Value : UInt24) is FB : FB24 with Import, Address => Frame_Buffer_Array (Layer); X0 : LCD_Height_Range; Y0 : LCD_Width_Range; Ok : Boolean; begin Convert (X, Y, Ok, X0, Y0); if Ok then -- Red: FB (Y0, (X0 * 3) + 2) := Byte (Value and 16#FF#); -- Green: FB (Y0, (X0 * 3) + 1) := Byte ((Value and 16#FF00#) / (2 ** 8)); -- Blue: FB (Y0, (X0 * 3) + 0) := Byte ((Value and 16#FF0000#) / (2 ** 16)); end if; end Set_Pixel; --------------- -- Set_Pixel -- --------------- procedure Set_Pixel (Layer : LCD_Layer; X : Natural; Y : Natural; Value : Half_Word) is FB : FB16 with Import, Address => Frame_Buffer_Array (Layer); X0 : LCD_Height_Range; Y0 : LCD_Width_Range; Ok : Boolean; begin Convert (X, Y, Ok, X0, Y0); if Ok then FB (Y0, X0) := Value; end if; end Set_Pixel; ----------------- -- Pixel_Value -- ----------------- function Pixel_Value (Layer : LCD_Layer; X : Natural; Y : Natural) return Word is FB : FB32 with Import, Address => Frame_Buffer_Array (Layer); X0 : LCD_Height_Range; Y0 : LCD_Width_Range; Ok : Boolean; begin Convert (X, Y, Ok, X0, Y0); if Ok then return FB (Y0, X0); else return 0; end if; end Pixel_Value; ----------------- -- Pixel_Value -- ----------------- function Pixel_Value (Layer : LCD_Layer; X : Natural; Y : Natural) return UInt24 is FB : FB24 with Import, Address => Frame_Buffer_Array (Layer); X0 : LCD_Height_Range; Y0 : LCD_Width_Range; Ok : Boolean; begin Convert (X, Y, Ok, X0, Y0); if Ok then return UInt24 (FB (Y0, X0 * 3 + 2)) or UInt24 (FB (Y0, X0 * 3 + 1)) * 2 ** 8 or UInt24 (FB (Y0, X0 * 3 + 0)) * 2 ** 16; else return 0; end if; end Pixel_Value; ----------------- -- Pixel_Value -- ----------------- function Pixel_Value (Layer : LCD_Layer; X : Natural; Y : Natural) return Half_Word is FB : FB16 with Import, Address => Frame_Buffer_Array (Layer); X0 : LCD_Height_Range; Y0 : LCD_Width_Range; Ok : Boolean; begin Convert (X, Y, Ok, X0, Y0); if Ok then return FB (Y0, X0); else return 0; end if; end Pixel_Value; end STM32.LTDC;
fix soft x-y swap, factorize.
stm32-ltdc: fix soft x-y swap, factorize.
Ada
bsd-3-clause
lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
3d1e9f7cd0508dd382fdd9677400ffad1880ab6c
awa/awaunit/awa-tests-helpers-users.adb
awa/awaunit/awa-tests-helpers-users.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Permission_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Log.Loggers; with AWA.Applications; with AWA.Tests; with AWA.Users.Modules; with ADO.Sessions; with ADO.SQL; package body AWA.Tests.Helpers.Users is use AWA.Users.Services; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Tests.Helpers.Users"); -- ------------------------------ -- Initialize the service context. -- ------------------------------ procedure Initialize (Principal : in out Test_User) is begin -- Setup the service context. Principal.Context.Set_Context (AWA.Tests.Get_Application, null); if Principal.Manager = null then Principal.Manager := AWA.Users.Modules.Get_User_Manager; if Principal.Manager = null then Log.Error ("There is no User_Manager in the application."); end if; end if; end Initialize; -- ------------------------------ -- Create a test user associated with the given email address. -- Get an open session for that user. If the user already exists, no error is reported. -- ------------------------------ procedure Create_User (Principal : in out Test_User; Email : in String) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the user Query.Set_Join ("inner join email e on e.user_id = o.id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Principal.User.Find (DB, Query, Found); if not Found then Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); else Principal.Manager.Authenticate (Email => Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); end if; Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Create a test user for a new test and get an open session. -- ------------------------------ procedure Create_User (Principal : in out Test_User) is Key : AWA.Users.Models.Access_Key_Ref; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; begin Initialize (Principal); Principal.User.Set_First_Name ("Joe"); Principal.User.Set_Last_Name ("Pot"); Principal.User.Set_Password ("admin"); Principal.Email.Set_Email (Email); Principal.Manager.Create_User (Principal.User, Principal.Email); Find_Access_Key (Principal, Email, Key); -- Run the verification and get the user and its session Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1", Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Create_User; -- ------------------------------ -- Find the access key associated with a user (if any). -- ------------------------------ procedure Find_Access_Key (Principal : in out Test_User; Email : in String; Key : in out AWA.Users.Models.Access_Key_Ref) is DB : ADO.Sessions.Session; Query : ADO.SQL.Query; Found : Boolean; begin Initialize (Principal); DB := Principal.Manager.Get_Session; -- Find the access key Query.Set_Join ("inner join email e on e.user_id = o.user_id"); Query.Set_Filter ("e.email = ?"); Query.Bind_Param (1, Email); Key.Find (DB, Query, Found); if not Found then Log.Error ("Cannot find access key for email {0}", Email); end if; end Find_Access_Key; -- ------------------------------ -- Login a user and create a session -- ------------------------------ procedure Login (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Authenticate (Email => Principal.Email.Get_Email, Password => "admin", IpAddr => "192.168.1.1", Principal => Principal.Principal); Principal.User := Principal.Principal.Get_User; Principal.Session := Principal.Principal.Get_Session; end Login; -- ------------------------------ -- Logout the user and closes the current session. -- ------------------------------ procedure Logout (Principal : in out Test_User) is begin Initialize (Principal); Principal.Manager.Close_Session (Principal.Session.Get_Id, True); end Logout; -- Simulate a user login in the given service context. procedure Login (Context : in out AWA.Services.Contexts.Service_Context; Sec_Context : in out Security.Contexts.Security_Context; Email : in String) is User : Test_User; Principal : AWA.Users.Principals.Principal_Access; App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application; begin AWA.Tests.Set_Application_Context; Create_User (User, Email); Principal := AWA.Users.Principals.Create (User.User, User.Session); Context.Set_Context (App, Principal); Sec_Context.Set_Context (Manager => App.Get_Security_Manager, Principal => Principal.all'Access); end Login; overriding procedure Finalize (Principal : in out Test_User) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Users.Principals.Principal'Class, Name => AWA.Users.Principals.Principal_Access); begin Free (Principal.Principal); end Finalize; end AWA.Tests.Helpers.Users;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
33ab9926e1c0a2c4d1e21e13349a2afa472dc2c6
regtests/asf-contexts-writer-tests.adb
regtests/asf-contexts-writer-tests.adb
----------------------------------------------------------------------- -- Writer Tests - Unit tests for ASF.Contexts.Writer -- 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 Ada.Calendar; with Ada.Unchecked_Deallocation; with Util.Tests; with Util.Test_Caller; package body ASF.Contexts.Writer.Tests is use Util.Tests; procedure Free_Writer is new Ada.Unchecked_Deallocation (Object => Test_Writer'Class, Name => Test_Writer_Access); procedure Initialize (Stream : in out Test_Writer; Content_Type : in String; Encoding : in String; Size : in Natural) is Output : ASF.Streams.Print_Stream; begin Stream.Content.Initialize (Size => Size); Output.Initialize (Stream.Content'Unchecked_Access); Stream.Initialize (Content_Type, Encoding, Output); end Initialize; overriding procedure Write (Stream : in out Test_Writer; Buffer : in Ada.Streams.Stream_Element_Array) is begin for I in Buffer'Range loop Append (Stream.Response, Character'Val (Buffer (I))); end loop; end Write; overriding procedure Flush (Stream : in out Test_Writer) is begin Response_Writer (Stream).Flush; Stream.Content.Read (Into => Stream.Response); end Flush; -- Set up performed before each test case overriding procedure Set_Up (T : in out Test) is begin T.Writer := new Test_Writer; -- use a small buffer to test the flush T.Writer.Initialize ("text/xml", "UTF-8", 1024); end Set_Up; -- Tear down performed after each test case overriding procedure Tear_Down (T : in out Test) is begin Free_Writer (T.Writer); end Tear_Down; -- Test the Start/Write/End_Element methods procedure Test_Write_Element (T : in out Test) is begin T.Writer.Start_Element ("p"); T.Writer.Start_Element ("b"); T.Writer.Write_Element ("i", "italic within a bold"); T.Writer.End_Element ("b"); T.Writer.End_Element ("p"); T.Writer.Flush; Assert_Equals (T, "<p><b><i>italic within a bold</i></b></p>", T.Writer.Response); T.Writer.Response := To_Unbounded_String (""); T.Writer.Start_Element ("div"); T.Writer.Write_Attribute ("title", "A ""S&'%^&<>"); T.Writer.Write_Attribute ("id", "23"); T.Writer.End_Element ("div"); T.Writer.Flush; Assert_Equals (T, "<div title=""A &quot;S&amp;'%^&amp;&lt;&gt;"" id=""23""></div>", T.Writer.Response); end Test_Write_Element; -- Test the Write_Char/Text methods procedure Test_Write_Text (T : in out Test) is use Ada.Calendar; Start : Ada.Calendar.Time; D : Duration; begin Start := Ada.Calendar.Clock; T.Writer.Start_Element ("p"); T.Writer.Write_Char ('<'); T.Writer.Write_Char ('>'); T.Writer.Write_Char ('~'); T.Writer.Start_Element ("i"); T.Writer.Write_Text ("""A' <>&"); T.Writer.End_Element ("i"); T.Writer.End_Element ("p"); T.Writer.Flush; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Write text: " & Duration'Image (D)); Assert_Equals (T, "<p>&lt;&gt;~<i>""A' &lt;&gt;&amp;</i></p>", T.Writer.Response); end Test_Write_Text; package Caller is new Util.Test_Caller (Test, "Contexts.Writer"); 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.Contexts.Writer.Start_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.End_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Attribute", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Text", Test_Write_Text'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Char", Test_Write_Text'Access); end Add_Tests; end ASF.Contexts.Writer.Tests;
----------------------------------------------------------------------- -- Writer Tests - Unit tests for ASF.Contexts.Writer -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Ada.Unchecked_Deallocation; with Util.Test_Caller; package body ASF.Contexts.Writer.Tests is use Util.Tests; procedure Free_Writer is new Ada.Unchecked_Deallocation (Object => Test_Writer'Class, Name => Test_Writer_Access); procedure Initialize (Stream : in out Test_Writer; Content_Type : in String; Encoding : in String; Size : in Natural) is Output : ASF.Streams.Print_Stream; begin Stream.Content.Initialize (Size => Size); Output.Initialize (Stream.Content'Unchecked_Access); Stream.Initialize (Content_Type, Encoding, Output); end Initialize; overriding procedure Write (Stream : in out Test_Writer; Buffer : in Ada.Streams.Stream_Element_Array) is begin for I in Buffer'Range loop Append (Stream.Response, Character'Val (Buffer (I))); end loop; end Write; overriding procedure Flush (Stream : in out Test_Writer) is begin Response_Writer (Stream).Flush; Stream.Content.Read (Into => Stream.Response); end Flush; -- Set up performed before each test case overriding procedure Set_Up (T : in out Test) is begin T.Writer := new Test_Writer; -- use a small buffer to test the flush T.Writer.Initialize ("text/xml", "UTF-8", 1024); end Set_Up; -- Tear down performed after each test case overriding procedure Tear_Down (T : in out Test) is begin Free_Writer (T.Writer); end Tear_Down; -- Test the Start/Write/End_Element methods procedure Test_Write_Element (T : in out Test) is begin T.Writer.Start_Element ("p"); T.Writer.Start_Element ("b"); T.Writer.Write_Element ("i", "italic within a bold"); T.Writer.End_Element ("b"); T.Writer.End_Element ("p"); T.Writer.Flush; Assert_Equals (T, "<p><b><i>italic within a bold</i></b></p>", T.Writer.Response); T.Writer.Response := To_Unbounded_String (""); T.Writer.Start_Element ("div"); T.Writer.Write_Attribute ("title", "A ""S&'%^&<>"); T.Writer.Write_Attribute ("id", "23"); T.Writer.End_Element ("div"); T.Writer.Flush; Assert_Equals (T, "<div title=""A &quot;S&amp;'%^&amp;&lt;&gt;"" id=""23""></div>", T.Writer.Response); end Test_Write_Element; -- Test the Write_Char/Text methods procedure Test_Write_Text (T : in out Test) is use Ada.Calendar; Start : Ada.Calendar.Time; D : Duration; begin Start := Ada.Calendar.Clock; T.Writer.Start_Element ("p"); T.Writer.Write_Char ('<'); T.Writer.Write_Char ('>'); T.Writer.Write_Char ('~'); T.Writer.Start_Element ("i"); T.Writer.Write_Text ("""A' <>&"); T.Writer.End_Element ("i"); T.Writer.End_Element ("p"); T.Writer.Flush; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Write text: " & Duration'Image (D)); Assert_Equals (T, "<p>&lt;&gt;~<i>""A' &lt;&gt;&amp;</i></p>", T.Writer.Response); end Test_Write_Text; package Caller is new Util.Test_Caller (Test, "Contexts.Writer"); 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.Contexts.Writer.Start_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.End_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Element", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Attribute", Test_Write_Element'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Text", Test_Write_Text'Access); Caller.Add_Test (Suite, "Test ASF.Contexts.Writer.Write_Char", Test_Write_Text'Access); end Add_Tests; end ASF.Contexts.Writer.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
463c5d2e4a4453c7e5ac47c39ce6a7908bef774d
mat/src/mat-targets.ads
mat/src/mat-targets.ads
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Ada.Finalization; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Events.Targets; with MAT.Readers.Streams.Sockets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is recieved. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Events : MAT.Events.Targets.Target_Events_Access; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is new Ada.Finalization.Limited_Controlled with private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is new Ada.Finalization.Limited_Controlled with record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; end MAT.Targets;
----------------------------------------------------------------------- -- mat-targets - Representation of target information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Ordered_Maps; with Ada.Finalization; with GNAT.Sockets; with MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Events.Targets; with MAT.Readers.Streams.Sockets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is -- Exception raised if some option is invalid. Usage_Error : exception; -- The options that can be configured through the command line. type Options_Type is record -- Enable and enter in the interactive TTY console mode. Interactive : Boolean := True; -- Try to load the symbol file automatically when a new process is recieved. Load_Symbols : Boolean := True; -- Enable the graphical mode (when available). Graphical : Boolean := False; -- Define the server listening address. Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Path : Ada.Strings.Unbounded.Unbounded_String; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Events : MAT.Events.Targets.Target_Events_Access; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is new Ada.Finalization.Limited_Controlled with private; type Target_Type_Access is access all Target_Type'Class; -- Get the console instance. function Console (Target : in Target_Type) return MAT.Consoles.Console_Access; -- Set the console instance. procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access); -- Get the current process instance. function Process (Target : in Target_Type) return Target_Process_Type_Access; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class); -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access); -- Find the process instance from the process ID. function Find_Process (Target : in Target_Type; Pid : in MAT.Types.Target_Process_Ref) return Target_Process_Type_Access; -- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure. procedure Iterator (Target : in Target_Type; Process : access procedure (Proc : in Target_Process_Type'Class)); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out Target_Type); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type); -- Start the server to listen to MAT event socket streams. procedure Start (Target : in out Target_Type); -- Stop the server thread. procedure Stop (Target : in out Target_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; private -- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id. -- This map allows to retrieve the information about a process. use type MAT.Types.Target_Process_Ref; package Process_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref, Element_Type => Target_Process_Type_Access); subtype Process_Map is Process_Maps.Map; subtype Process_Cursor is Process_Maps.Cursor; type Target_Type is new Ada.Finalization.Limited_Controlled with record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; Options : Options_Type; Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type; end record; end MAT.Targets;
Declare the Iterator procedure to iterate over the processes
Declare the Iterator procedure to iterate over the processes
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
60c3c26a82b445659b6f524bc6a5b5fad175baaf
src/security-auth-oauth.adb
src/security-auth-oauth.adb
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body Security.Auth.OAuth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth"); -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. -- ------------------------------ -- Initialize the authentication realm. -- ------------------------------ overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID) is begin Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id")); Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret")); Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url")); Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url")); Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm")); Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope")); Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer")); end Initialize; -- ------------------------------ -- 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. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) -- ------------------------------ overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is pragma Unreferenced (Realm); begin Result.URL := To_Unbounded_String (Name); end Discover; -- ------------------------------ -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) -- ------------------------------ overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association) is pragma Unreferenced (Realm, OP); begin Result.Assoc_Handle := To_Unbounded_String (Security.OAuth.Clients.Create_Nonce (128)); end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is Result : Unbounded_String := OP.URL; State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle)); Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope)); begin if Index (Result, "?") > 0 then Append (Result, "&"); else Append (Result, "?"); end if; Append (Result, Params); Append (Result, "&"); Append (Result, Security.OAuth.RESPONSE_TYPE); Append (Result, "=code"); Log.Debug ("Params = {0}", Params); return To_String (Result); end Get_Authentication_URL; -- ------------------------------ -- Verify the authentication result -- ------------------------------ overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is State : constant String := Request.Get_Parameter (Security.OAuth.STATE); Code : constant String := Request.Get_Parameter (Security.OAuth.CODE); Error : constant String := Request.Get_Parameter (Security.OAuth.ERROR_DESCRIPTION); begin if Error'Length /= 0 then Set_Result (Result, CANCEL, "Authentication refused: " & Error); return; end if; -- First, verify that the state parameter matches our internal state. if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter"); return; end if; -- Get the access token from the authorization code. declare use type Security.OAuth.Clients.Access_Token_Access; Acc : constant Security.OAuth.Clients.Access_Token_Access := Realm.App.Request_Access_Token (Code); begin if Acc = null then Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token"); return; end if; -- Last step, verify the access token and get the user identity. Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result); end; end Verify; end Security.Auth.OAuth;
----------------------------------------------------------------------- -- security-auth-oauth -- OAuth based authentication -- Copyright (C) 2013, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body Security.Auth.OAuth is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth"); -- ------------------------------ -- OAuth Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OAuth authorization process. -- ------------------------------ -- Initialize the authentication realm. -- ------------------------------ overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID) is begin Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id")); Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret")); Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url")); Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url")); Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm")); Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope")); Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer")); end Initialize; -- ------------------------------ -- 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. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) -- ------------------------------ overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point) is pragma Unreferenced (Realm); begin Result.URL := To_Unbounded_String (Name); end Discover; -- ------------------------------ -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) -- ------------------------------ overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association) is pragma Unreferenced (Realm, OP); begin Result.Assoc_Handle := To_Unbounded_String (Security.OAuth.Clients.Create_Nonce (128)); Result.Nonce := To_Unbounded_String (Security.OAuth.Clients.Create_Nonce (256)); end Associate; -- ------------------------------ -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. -- ------------------------------ overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String is Result : Unbounded_String := OP.URL; State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle)); Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope)); begin if Index (Result, "?") > 0 then Append (Result, "&"); else Append (Result, "?"); end if; Append (Result, Params); Append (Result, "&"); Append (Result, Security.OAuth.RESPONSE_TYPE); Append (Result, "=code"); Append (Result, "&"); Append (Result, Security.OAuth.NONCE_TOKEN); Append (Result, "="); Append (Result, Assoc.Nonce); Log.Debug ("Params = {0}", Params); return To_String (Result); end Get_Authentication_URL; -- ------------------------------ -- Verify the authentication result -- ------------------------------ overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication) is State : constant String := Request.Get_Parameter (Security.OAuth.STATE); Code : constant String := Request.Get_Parameter (Security.OAuth.CODE); Error : constant String := Request.Get_Parameter (Security.OAuth.ERROR_DESCRIPTION); begin if Error'Length /= 0 then Set_Result (Result, CANCEL, "Authentication refused: " & Error); return; end if; -- First, verify that the state parameter matches our internal state. if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter"); return; end if; -- Get the access token from the authorization code. declare use type Security.OAuth.Clients.Access_Token_Access; Acc : constant Security.OAuth.Clients.Access_Token_Access := Realm.App.Request_Access_Token (Code); begin if Acc = null then Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token"); return; end if; -- Last step, verify the access token and get the user identity. Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result); end; end Verify; end Security.Auth.OAuth;
Create a nonce when the association is built and add it to the OAuth2 request
Create a nonce when the association is built and add it to the OAuth2 request
Ada
apache-2.0
stcarrez/ada-security
0ab958653ab0f6b5128125155e994c55f3d588ed
src/core/util-nullables.ads
src/core/util-nullables.ads
----------------------------------------------------------------------- -- util-nullables -- Basic types that can hold a null value -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; -- === Nullable types === -- Sometimes it is necessary to represent a simple data type with an optional boolean information -- that indicates whether the value is valid or just null. The concept of nullable type is often -- used in databases but also in JSON data representation. The <tt>Util.Nullables</tt> package -- provides several standard type to express the null capability of a value. -- -- By default a nullable instance is created with the null flag set. package Util.Nullables is use type Ada.Strings.Unbounded.Unbounded_String; use type Ada.Calendar.Time; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- A boolean which can be null. -- ------------------------------ type Nullable_Boolean is record Value : Boolean := False; Is_Null : Boolean := True; end record; Null_Boolean : constant Nullable_Boolean; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Boolean) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- An integer which can be null. -- ------------------------------ type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; Null_Integer : constant Nullable_Integer; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Integer) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A long which can be null. -- ------------------------------ type Nullable_Long is record Value : Long_Long_Integer := 0; Is_Null : Boolean := True; end record; Null_Long : constant Nullable_Long; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Long) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A string which can be null. -- ------------------------------ type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; Null_String : constant Nullable_String; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_String) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A date which can be null. -- ------------------------------ type Nullable_Time is record Value : Ada.Calendar.Time := DEFAULT_TIME; Is_Null : Boolean := True; end record; Null_Time : constant Nullable_Time; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean is (Left.Is_Null = Right.Is_Null and (Left.Is_Null or else Left.Value = Right.Value)); private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); Null_Boolean : constant Nullable_Boolean := Nullable_Boolean '(Is_Null => True, Value => False); Null_Integer : constant Nullable_Integer := Nullable_Integer '(Is_Null => True, Value => 0); Null_Long : constant Nullable_Long := Nullable_Long '(Is_Null => True, Value => 0); Null_String : constant Nullable_String := Nullable_String '(Is_Null => True, Value => Ada.Strings.Unbounded.Null_Unbounded_String); Null_Time : constant Nullable_Time := Nullable_Time '(Is_Null => True, Value => DEFAULT_TIME); end Util.Nullables;
----------------------------------------------------------------------- -- util-nullables -- Basic types that can hold a null value -- Copyright (C) 2017, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; -- === Nullable types === -- Sometimes it is necessary to represent a simple data type with an optional boolean information -- that indicates whether the value is valid or just null. The concept of nullable type is often -- used in databases but also in JSON data representation. The <tt>Util.Nullables</tt> package -- provides several standard type to express the null capability of a value. -- -- By default a nullable instance is created with the null flag set. package Util.Nullables is use type Ada.Strings.Unbounded.Unbounded_String; use type Ada.Calendar.Time; DEFAULT_TIME : constant Ada.Calendar.Time; -- ------------------------------ -- A boolean which can be null. -- ------------------------------ type Nullable_Boolean is record Value : Boolean := False; Is_Null : Boolean := True; end record; Null_Boolean : constant Nullable_Boolean; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Boolean) return Boolean is ((Left.Is_Null = Right.Is_Null) and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- An integer which can be null. -- ------------------------------ type Nullable_Integer is record Value : Integer := 0; Is_Null : Boolean := True; end record; Null_Integer : constant Nullable_Integer; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Integer) return Boolean is ((Left.Is_Null = Right.Is_Null) and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A long which can be null. -- ------------------------------ type Nullable_Long is record Value : Long_Long_Integer := 0; Is_Null : Boolean := True; end record; Null_Long : constant Nullable_Long; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_Long) return Boolean is ((Left.Is_Null = Right.Is_Null) and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A string which can be null. -- ------------------------------ type Nullable_String is record Value : Ada.Strings.Unbounded.Unbounded_String; Is_Null : Boolean := True; end record; Null_String : constant Nullable_String; -- Return True if the two nullable times are identical (both null or both same value). function "=" (Left, Right : in Nullable_String) return Boolean is ((Left.Is_Null = Right.Is_Null) and (Left.Is_Null or else Left.Value = Right.Value)); -- ------------------------------ -- A date which can be null. -- ------------------------------ type Nullable_Time is record Value : Ada.Calendar.Time := DEFAULT_TIME; Is_Null : Boolean := True; end record; Null_Time : constant Nullable_Time; -- Return True if the two nullable times are identical (both null or both same time). function "=" (Left, Right : in Nullable_Time) return Boolean is ((Left.Is_Null = Right.Is_Null) and (Left.Is_Null or else Left.Value = Right.Value)); private DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901, Month => 1, Day => 2, Seconds => 0.0); Null_Boolean : constant Nullable_Boolean := Nullable_Boolean '(Is_Null => True, Value => False); Null_Integer : constant Nullable_Integer := Nullable_Integer '(Is_Null => True, Value => 0); Null_Long : constant Nullable_Long := Nullable_Long '(Is_Null => True, Value => 0); Null_String : constant Nullable_String := Nullable_String '(Is_Null => True, Value => Ada.Strings.Unbounded.Null_Unbounded_String); Null_Time : constant Nullable_Time := Nullable_Time '(Is_Null => True, Value => DEFAULT_TIME); end Util.Nullables;
Fix compilation warning with GNAT 2021
Fix compilation warning with GNAT 2021
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b815907911c6dce7069ef96067d5cb923554e7c0
samples/variables.adb
samples/variables.adb
----------------------------------------------------------------------- -- el -- Evaluate an EL expression -- Copyright (C) 2009, 2010 Free Software Foundation, Inc. -- Written by Stephane Carrez ([email protected]) -- -- This file is part of ASF. -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License as -- published by the Free Software Foundation; either version 2, -- or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; see the file COPYING. If not, write to -- the Free Software Foundation, 59 Temple Place - Suite 330, -- Boston, MA 02111-1307, USA. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with EL.Beans; with Ada.Text_IO; with Bean; procedure Variables is use Bean; Joe : Person_Access := Create_Person ("Joe", "Smith", 12); Bill : Person_Access := Create_Person ("Bill", "Johnson", 42); Ctx : EL.Contexts.Default.Default_Context; E : EL.Expressions.Expression; Result : EL.Objects.Object; begin E := EL.Expressions.Create_Expression ("#{user.firstName} #{user.lastName}", Ctx); -- Bind the context to 'Joe' and evaluate Ctx.Set_Variable ("user", Joe); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("Joe's name is " & EL.Objects.To_String (Result)); -- Bind the context to 'Bill' and evaluate Ctx.Set_Variable ("user", Bill); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("Bill's name is " & EL.Objects.To_String (Result)); Free (Joe); Free (Bill); end Variables;
----------------------------------------------------------------------- -- el -- Evaluate an EL expression -- Copyright (C) 2009, 2010 Free Software Foundation, Inc. -- Written by Stephane Carrez ([email protected]) -- -- This file is part of ASF. -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License as -- published by the Free Software Foundation; either version 2, -- or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; see the file COPYING. If not, write to -- the Free Software Foundation, 59 Temple Place - Suite 330, -- Boston, MA 02111-1307, USA. ----------------------------------------------------------------------- with EL.Expressions; with EL.Objects; with EL.Contexts.Default; with Ada.Text_IO; with Bean; procedure Variables is use Bean; Joe : Person_Access := Create_Person ("Joe", "Smith", 12); Bill : Person_Access := Create_Person ("Bill", "Johnson", 42); Ctx : EL.Contexts.Default.Default_Context; E : EL.Expressions.Expression; VE : EL.Expressions.Value_Expression; Result : EL.Objects.Object; begin E := EL.Expressions.Create_Expression ("#{user.firstName} #{user.lastName}", Ctx); -- Bind the context to 'Joe' and evaluate Ctx.Set_Variable ("user", Joe); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result)); -- Bind the context to 'Bill' and evaluate Ctx.Set_Variable ("user", Bill); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result)); -- Create a value expression to change the user firstName property. VE := EL.Expressions.Create_Expression ("#{user.firstName}", Ctx); -- Change the user first name by setting the value expression. VE.Set_Value (Context => Ctx, Value => EL.Objects.To_Object (String '("Harold"))); Result := E.Get_Value (Ctx); Ada.Text_IO.Put_Line ("User name is " & EL.Objects.To_String (Result)); Free (Joe); Free (Bill); end Variables;
Add an example of Value_Expression and call to Set_Value
Add an example of Value_Expression and call to Set_Value
Ada
apache-2.0
Letractively/ada-el
1964a74aa709d38579ffa8103affb49628775c4f
src/babel-files-buffers.ads
src/babel-files-buffers.ads
----------------------------------------------------------------------- -- babel-files-buffers -- File buffer management -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Containers.Vectors; with Util.Concurrent.Pools; package Babel.Files.Buffers is type Buffer; type Buffer_Access is access all Buffer; package Buffer_Pools is new Util.Concurrent.Pools (Element_Type => Buffer_Access); type Buffer_Pool_Access is access all Buffer_Pools.Pool; type Buffer (Max_Size : Ada.Streams.Stream_Element_Offset; Pool : Buffer_Pool_Access) is limited record Last : Ada.Streams.Stream_Element_Offset; Data : Ada.Streams.Stream_Element_Array (0 .. Max_Size); end record; -- Restore the buffer back to the owning pool. procedure Release (Buffer : in out Buffer_Access); -- Create the buffer pool with a number of pre-allocated buffers of the given maximum size. procedure Create_Pool (Into : in out Buffer_Pools.Pool; Size : in Positive; Count : in Positive); package Buffer_Access_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Buffer_Access, "=" => "="); subtype Buffer_Access_Vector is Buffer_Access_Vectors.Vector; subtype Buffer_Access_Cursor is Buffer_Access_Vectors.Cursor; end Babel.Files.Buffers;
----------------------------------------------------------------------- -- babel-files-buffers -- File buffer management -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Containers.Vectors; with Util.Concurrent.Pools; package Babel.Files.Buffers is type Buffer; type Buffer_Access is access all Buffer; package Buffer_Pools is new Util.Concurrent.Pools (Element_Type => Buffer_Access); subtype Buffer_Pool is Buffer_Pools.Pool; type Buffer_Pool_Access is access all Buffer_Pool; type Buffer (Max_Size : Ada.Streams.Stream_Element_Offset; Pool : Buffer_Pool_Access) is limited record Last : Ada.Streams.Stream_Element_Offset; Data : Ada.Streams.Stream_Element_Array (0 .. Max_Size); end record; -- Restore the buffer back to the owning pool. procedure Release (Buffer : in out Buffer_Access); -- Create the buffer pool with a number of pre-allocated buffers of the given maximum size. procedure Create_Pool (Into : in out Buffer_Pools.Pool; Size : in Positive; Count : in Positive); package Buffer_Access_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Buffer_Access, "=" => "="); subtype Buffer_Access_Vector is Buffer_Access_Vectors.Vector; subtype Buffer_Access_Cursor is Buffer_Access_Vectors.Cursor; end Babel.Files.Buffers;
Define the Buffer_Pool type
Define the Buffer_Pool type
Ada
apache-2.0
stcarrez/babel
cdb056531fe10f8030313deebdd7d681936f2ec1
matp/src/events/mat-events-targets.adb
matp/src/events/mat-events-targets.adb
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Probe_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); 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 start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- 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; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; 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.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Start <= Finish then if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos > Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); else if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id < Finish; Id := Id - 1; if Pos = Block.Events'First then Event_Id_Maps.Previous (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Count; else Pos := Pos - 1; end if; end loop; end if; Event_Id_Maps.Previous (Iter); end if; end loop; end Iterate; end Event_Collector; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. -- ------------------------------ function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Probe_Event_Type is Iter : Target_Event_Cursor := List.First; Event : Probe_Event_Type; begin while Target_Event_Vectors.Has_Element (Iter) loop Event := Target_Event_Vectors.Element (Iter); if Event.Index = Kind then return Event; end if; Target_Event_Vectors.Next (Iter); end loop; raise Not_Found; end Find; -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); 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 start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (Target : in out Target_Events; First : out Probe_Event_Type; Last : out Probe_Event_Type) is begin Target.Events.Get_Limits (First, Last); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- 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; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is begin Target.Events.Iterate (Start, Finish, Process); end Iterate; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; 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.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the first and last event that have been received. -- ------------------------------ procedure Get_Limits (First : out Probe_Event_Type; Last : out Probe_Event_Type) is First_Block : constant Event_Block_Access := Events.First_Element; Last_Block : constant Event_Block_Access := Events.Last_Element; begin First := First_Block.Events (First_Block.Events'First); Last := Last_Block.Events (Last_Block.Count); end Get_Limits; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Pos <= Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; -- ------------------------------ -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. -- ------------------------------ procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)) is Iter : Event_Id_Cursor := Ids.Floor (Start); Block : Event_Block_Access; Pos : Event_Id_Type; Id : Event_Id_Type := Start; begin -- First, find the block and position of the first event. while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id + Block.Events'First; if Start <= Finish then if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id > Finish; Pos := Pos + 1; Id := Id + 1; if Pos > Block.Count then Event_Id_Maps.Next (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Events'First; end if; end loop; end if; Event_Id_Maps.Next (Iter); else if Pos <= Block.Count then -- Second, iterate over the events moving to the next event block -- until we reach the last event. loop Process (Block.Events (Pos)); exit when Id <= Finish; Id := Id - 1; if Pos = Block.Events'First then Event_Id_Maps.Previous (Iter); exit when not Event_Id_Maps.Has_Element (Iter); Block := Event_Id_Maps.Element (Iter); Pos := Block.Count; else Pos := Pos - 1; end if; end loop; end if; Event_Id_Maps.Previous (Iter); end if; end loop; end Iterate; end Event_Collector; end MAT.Events.Targets;
Fix the event backward search
Fix the event backward search
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4c236d131b12a7d664981a06562530d8982dbaeb
awa/src/awa-users-modules.ads
awa/src/awa-users-modules.ads
----------------------------------------------------------------------- -- awa-users-module -- User management module -- 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 ASF.Applications; with ASF.Security.Servlets; with AWA.Modules; with AWA.Users.Services; with AWA.Users.Filters; with AWA.Users.Servlets; -- == Introduction == -- The <b>Users.Module</b> manages the creation, update, removal and authentication of users -- in an application. The module provides the foundations for user management in -- a web application. -- -- A user can register himself by using a subscription form. In that case, a verification mail -- is sent and the user has to follow the verification link defined in the mail to finish -- the registration process. The user will authenticate using a password. -- -- A user can also use an OpenID account and be automatically registered. -- -- A user can have one or several permissions that allow to protect the application data. -- User permissions are managed by the <b>Permissions.Module</b>. -- -- == Configuration == -- The *users* module uses a set of configuration properties to configure the OpenID -- integration. -- -- @include users.xml -- -- @include awa-users-services.ads -- -- @include users.xml -- -- == Data Model == -- @include User.hbm.xml package AWA.Users.Modules is NAME : constant String := "users"; type User_Module is new AWA.Modules.Module with private; type User_Module_Access is access all User_Module'Class; -- Initialize the user module. overriding procedure Initialize (Plugin : in out User_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the user manager. function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Create a user manager. This operation can be overriden to provide another -- user service implementation. function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Get the user module instance associated with the current application. function Get_User_Module return User_Module_Access; -- Get the user manager instance associated with the current application. function Get_User_Manager return Services.User_Service_Access; private type User_Module is new AWA.Modules.Module with record Manager : Services.User_Service_Access := null; Key_Filter : aliased AWA.Users.Filters.Verify_Filter; Auth_Filter : aliased AWA.Users.Filters.Auth_Filter; Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; end record; end AWA.Users.Modules;
----------------------------------------------------------------------- -- awa-users-module -- User management module -- 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 ASF.Applications; with ASF.Security.Servlets; with AWA.Modules; with AWA.Users.Services; with AWA.Users.Filters; with AWA.Users.Servlets; -- == Introduction == -- The <b>Users.Module</b> manages the creation, update, removal and authentication of users -- in an application. The module provides the foundations for user management in -- a web application. -- -- A user can register himself by using a subscription form. In that case, a verification mail -- is sent and the user has to follow the verification link defined in the mail to finish -- the registration process. The user will authenticate using a password. -- -- A user can also use an OpenID account and be automatically registered. -- -- A user can have one or several permissions that allow to protect the application data. -- User permissions are managed by the <b>Permissions.Module</b>. -- -- == Configuration == -- The *users* module uses a set of configuration properties to configure the OpenID -- integration. -- -- @include users.xml -- -- @include awa-users-services.ads -- -- @include users.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_user_model.png] -- -- @include User.hbm.xml package AWA.Users.Modules is NAME : constant String := "users"; type User_Module is new AWA.Modules.Module with private; type User_Module_Access is access all User_Module'Class; -- Initialize the user module. overriding procedure Initialize (Plugin : in out User_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the user manager. function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Create a user manager. This operation can be overriden to provide another -- user service implementation. function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Get the user module instance associated with the current application. function Get_User_Module return User_Module_Access; -- Get the user manager instance associated with the current application. function Get_User_Manager return Services.User_Service_Access; private type User_Module is new AWA.Modules.Module with record Manager : Services.User_Service_Access := null; Key_Filter : aliased AWA.Users.Filters.Verify_Filter; Auth_Filter : aliased AWA.Users.Filters.Auth_Filter; Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; end record; end AWA.Users.Modules;
Update the user module documentation
Update the user module documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b27f8b5bf4e6a6f23c35b70fd11b5dbaee0272f5
mat/src/events/mat-events-probes.adb
mat/src/events/mat-events-probes.adb
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Events.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes"); procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; Manager.Frames := MAT.Frames.Create_Root; end Initialize; -- ------------------------------ -- 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) is Handler : Probe_Handler; begin Handler.Probe := Probe; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Probes.Insert (Name, Handler); end Register_Probe; -- ------------------------------ -- Get the target events. -- ------------------------------ function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access is begin return Client.Events; end Get_Target_Events; procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Tick_Ref; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : constant access MAT.Events.Frame_Info := Client.Frame; begin Client.Event.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_THREAD_ID => Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_FRAME_PC => for I in 1 .. Count loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); end if; end loop; when others => null; end case; end; end loop; Client.Event.Time := MAT.Types.Target_Tick_Ref (Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32)); Client.Event.Time := Client.Event.Time or MAT.Types.Target_Tick_Ref (Time_Usec); Frame.Cur_Depth := Count; end Read_Probe; procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is use type MAT.Events.Attribute_Table_Ptr; use type MAT.Events.Targets.Target_Events_Access; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); end if; if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Probe_Handler := Handler_Maps.Element (Pos); begin Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); MAT.Frames.Insert (Frame => Client.Frames, Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth), Result => Client.Event.Frame); Client.Events.Insert (Client.Event); Handler.Probe.Execute (Client.Event); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True); end Dispatch_Message; -- ------------------------------ -- 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_Type) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name); Frame : Probe_Handler; procedure Add_Handler (Key : in String; Element : in out Probe_Handler); procedure Add_Handler (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0} with {1} attributes", Name, MAT.Types.Uint16'Image (Count)); if Name = "start" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("start", Frame); end if; end; end loop; if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- 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) is Count : MAT.Types.Uint16; begin if Client.Frame = null then Client.Frame := new MAT.Events.Frame_Info (512); end if; Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; exception when E : MAT.Readers.Marshaller.Buffer_Underflow_Error => Log.Error ("Not enough data in the message", E, True); end Read_Event_Definitions; end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Events.Probes is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes"); procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC), 7 => (Name => RUSAGE_MINFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MINFLT), 8 => (Name => RUSAGE_MAJFLT_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_MAJFLT), 9 => (Name => RUSAGE_NVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NVCSW), 10 => (Name => RUSAGE_NIVCSW_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_RUSAGE_NIVCSW) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Initialize the manager instance. -- ------------------------------ overriding procedure Initialize (Manager : in out Probe_Manager_Type) is begin Manager.Events := new MAT.Events.Targets.Target_Events; Manager.Frames := MAT.Frames.Create_Root; end Initialize; -- ------------------------------ -- 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) is Handler : Probe_Handler; begin Handler.Probe := Probe; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Probes.Insert (Name, Handler); end Register_Probe; -- ------------------------------ -- Get the target events. -- ------------------------------ function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access is begin return Client.Events; end Get_Target_Events; procedure Read_Probe (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message) is use type MAT.Types.Target_Tick_Ref; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : constant access MAT.Events.Frame_Info := Client.Frame; begin Client.Event.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind); when P_THREAD_ID => Client.Event.Thread := MAT.Types.Target_Thread_Ref (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind)); when P_FRAME_PC => for I in 1 .. Count loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind); end if; end loop; when others => null; end case; end; end loop; -- Convert the time in usec to make computation easier. Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000; Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec); Frame.Cur_Depth := Count; end Read_Probe; procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is use type MAT.Events.Attribute_Table_Ptr; use type MAT.Events.Targets.Target_Events_Access; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); end if; if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Probe_Handler := Handler_Maps.Element (Pos); begin Client.Event.Event := Event; Client.Event.Index := Handler.Id; Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event); MAT.Frames.Insert (Frame => Client.Frames, Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth), Result => Client.Event.Frame); Client.Events.Insert (Client.Event); Handler.Probe.Execute (Client.Event); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True); end Dispatch_Message; -- ------------------------------ -- 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_Type) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name); Frame : Probe_Handler; procedure Add_Handler (Key : in String; Element : in out Probe_Handler); procedure Add_Handler (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0} with {1} attributes", Name, MAT.Types.Uint16'Image (Count)); if Name = "start" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler); procedure Read_Attribute (Key : in String; Element : in out Probe_Handler) is pragma Unreferenced (Key); use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("start", Frame); end if; end; end loop; if Probe_Maps.Has_Element (Pos) then Client.Probes.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- 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) is Count : MAT.Types.Uint16; begin if Client.Frame = null then Client.Frame := new MAT.Events.Frame_Info (512); end if; Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; exception when E : MAT.Readers.Marshaller.Buffer_Underflow_Error => Log.Error ("Not enough data in the message", E, True); end Read_Event_Definitions; end MAT.Events.Probes;
Convert the time in usec to make computation easier
Convert the time in usec to make computation easier
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
df82ea2c39820e042c125498267f171cb2b14c28
awa/regtests/awa-testsuite.adb
awa/regtests/awa-testsuite.adb
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Blogs.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Modules.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Counters.Modules.Tests; with AWA.Workspaces.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with Servlet.Server; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; 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 AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Workspaces.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Modules.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); Application.Start; -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- Application.Add_Converter (Name => "dateConverter", -- Converter => Date_Converter'Access); -- Application.Add_Converter (Name => "smartDateConverter", -- Converter => Rel_Date_Converter'Access); -- -- WS.Register_Application ("/asfunit", Application.all'Access); -- -- WS.Start; -- delay 6000.0; -- end; -- end if; Servlet.Server.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
----------------------------------------------------------------------- -- Util testsuite - Util Testsuite -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Users.Services.Tests; with AWA.Users.Tests; with AWA.Blogs.Modules.Tests; with AWA.Blogs.Tests; with AWA.Helpers.Selectors.Tests; with AWA.Storages.Services.Tests; with AWA.Events.Services.Tests; with AWA.Mail.Clients.Tests; with AWA.Mail.Modules.Tests; with AWA.Images.Modules.Tests; with AWA.Votes.Modules.Tests; with AWA.Tags.Modules.Tests; with AWA.Questions.Modules.Tests; with AWA.Counters.Modules.Tests; with AWA.Workspaces.Tests; with AWA.Modules.Tests; with ASF.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Changelogs.Modules; with AWA.Counters.Modules; with AWA.Converters.Dates; with AWA.Tests; with AWA.Services.Contexts; with AWA.Jobs.Services.Tests; with AWA.Jobs.Modules.Tests; with AWA.Settings.Modules.Tests; with AWA.Comments.Modules.Tests; with AWA.Changelogs.Modules.Tests; with AWA.Wikis.Modules.Tests; with AWA.Wikis.Tests; with Servlet.Server; package body AWA.Testsuite is Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Jobs : aliased AWA.Jobs.Modules.Job_Module; Comments : aliased AWA.Comments.Modules.Comment_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Images : aliased AWA.Images.Modules.Image_Module; Questions : aliased AWA.Questions.Modules.Question_Module; Votes : aliased AWA.Votes.Modules.Vote_Module; Tags : aliased AWA.Tags.Modules.Tag_Module; Settings : aliased AWA.Settings.Modules.Setting_Module; Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module; Wikis : aliased AWA.Wikis.Modules.Wiki_Module; Counters : aliased AWA.Counters.Modules.Counter_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; 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 AWA.Modules.Tests.Add_Tests (Ret); AWA.Events.Services.Tests.Add_Tests (Ret); AWA.Mail.Clients.Tests.Add_Tests (Ret); AWA.Mail.Modules.Tests.Add_Tests (Ret); AWA.Users.Services.Tests.Add_Tests (Ret); AWA.Users.Tests.Add_Tests (Ret); AWA.Workspaces.Tests.Add_Tests (Ret); AWA.Counters.Modules.Tests.Add_Tests (Ret); AWA.Helpers.Selectors.Tests.Add_Tests (Ret); AWA.Jobs.Modules.Tests.Add_Tests (Ret); AWA.Jobs.Services.Tests.Add_Tests (Ret); AWA.Settings.Modules.Tests.Add_Tests (Ret); AWA.Comments.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Modules.Tests.Add_Tests (Ret); AWA.Blogs.Tests.Add_Tests (Ret); AWA.Storages.Services.Tests.Add_Tests (Ret); AWA.Images.Modules.Tests.Add_Tests (Ret); AWA.Changelogs.Modules.Tests.Add_Tests (Ret); AWA.Votes.Modules.Tests.Add_Tests (Ret); AWA.Tags.Modules.Tests.Add_Tests (Ret); AWA.Questions.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Modules.Tests.Add_Tests (Ret); AWA.Wikis.Tests.Add_Tests (Ret); return Ret; end Suite; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin AWA.Tests.Initialize (App, Props, Add_Modules); if Add_Modules then declare Application : constant Applications.Application_Access := AWA.Tests.Get_Application; Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Counters.Modules.NAME, URI => "counters", Module => Counters'Access); Register (App => Application.all'Access, Name => AWA.Comments.Modules.NAME, URI => "comments", Module => Comments'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Jobs.Modules.NAME, URI => "jobs", Module => Jobs'Access); Register (App => Application.all'Access, Name => AWA.Images.Modules.NAME, URI => "images", Module => Images'Access); Register (App => Application.all'Access, Name => AWA.Settings.Modules.NAME, URI => "settings", Module => Settings'Access); Register (App => Application.all'Access, Name => AWA.Votes.Modules.NAME, URI => "votes", Module => Votes'Access); Register (App => Application.all'Access, Name => AWA.Changelogs.Modules.NAME, URI => "changelogs", Module => Changelogs'Access); Register (App => Application.all'Access, Name => AWA.Tags.Modules.NAME, URI => "tags", Module => Tags'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); Register (App => Application.all'Access, Name => AWA.Questions.Modules.NAME, URI => "questions", Module => Questions'Access); Register (App => Application.all'Access, Name => AWA.Wikis.Modules.NAME, URI => "wikis", Module => Wikis'Access); Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); Application.Start; -- if Props.Exists ("test.server") then -- declare -- WS : ASF.Server.Web.AWS_Container; -- begin -- Application.Add_Converter (Name => "dateConverter", -- Converter => Date_Converter'Access); -- Application.Add_Converter (Name => "smartDateConverter", -- Converter => Rel_Date_Converter'Access); -- -- WS.Register_Application ("/asfunit", Application.all'Access); -- -- WS.Start; -- delay 6000.0; -- end; -- end if; Servlet.Server.Set_Context (Application.all'Access); end; end if; end Initialize; end AWA.Testsuite;
Add more unit tests for Wiki module
Add more unit tests for Wiki module
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9402f2c007f96358e69c4f9d64c629a9cd7b972e
awa/src/awa-users-services.ads
awa/src/awa-users-services.ads
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Permissions.Services; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); package User_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Users.Models.User_Ref'Class); subtype Listener is User_Lifecycle.Listener; NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class; Key : in String := ""); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); -- Create and generate a new access key for the user. The access key is saved in the -- database and it will expire after the expiration delay. procedure Create_Access_Key (Model : in out User_Service; User : in AWA.Users.Models.User_Ref'Class; Key : in out AWA.Users.Models.Access_Key_Ref; Kind : in AWA.Users.Models.Key_Type; Expire : in Duration; Session : in out ADO.Sessions.Master_Session); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; Permissions : AWA.Permissions.Services.Permission_Manager_Access; end record; end AWA.Users.Services;
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Permissions.Services; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); package User_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Users.Models.User_Ref'Class); subtype Listener is User_Lifecycle.Listener; NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class); -- Create a user in the database with the given user information and -- the associated email address and for the given access key. The access key is first -- verified and the user instance associated with it is retrieved. Verify that the email -- address is unique and can be used by the user. Since the access key is verified, -- grant immediately the access by opening a session and setting up the principal instance. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); -- Create and generate a new access key for the user. The access key is saved in the -- database and it will expire after the expiration delay. procedure Create_Access_Key (Model : in out User_Service; User : in AWA.Users.Models.User_Ref'Class; Key : in out AWA.Users.Models.Access_Key_Ref; Kind : in AWA.Users.Models.Key_Type; Expire : in Duration; Session : in out ADO.Sessions.Master_Session); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; Permissions : AWA.Permissions.Services.Permission_Manager_Access; end record; end AWA.Users.Services;
Declare a Create_User procedure to register a new user with an access key
Declare a Create_User procedure to register a new user with an access key
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d569d96149c189caf468624f8906674b2f435c6e
awa/src/awa-users-principals.ads
awa/src/awa-users-principals.ads
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with AWA.Users.Models; with ASF.Principals; with Security.Permissions; package AWA.Users.Principals is type Principal is new ASF.Principals.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Security.Permissions.Role_Type) return Boolean; -- Get the principal identifier (name) function Get_Id (From : in Principal) return String; -- Get the user associated with the principal. function Get_User (From : in Principal) return AWA.Users.Models.User_Ref; -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. function Get_User_Identifier (From : in Principal) return ADO.Identifier; -- Get the connection session used by the user. function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref; -- Get the connection session identifier used by the user. function Get_Session_Identifier (From : in Principal) return ADO.Identifier; -- Create a principal for the given user. function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access; -- Utility functions based on the security principal access type. -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. function Get_User_Identifier (From : in Security.Permissions.Principal_Access) return ADO.Identifier; private type Principal is new ASF.Principals.Principal with record User : AWA.Users.Models.User_Ref; Session : AWA.Users.Models.Session_Ref; Roles : Security.Permissions.Role_Map; end record; end AWA.Users.Principals;
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO; with AWA.Users.Models; with ASF.Principals; with Security.Permissions; package AWA.Users.Principals is type Principal is new ASF.Principals.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Security.Permissions.Role_Type) return Boolean; -- Get the principal identifier (name) function Get_Id (From : in Principal) return String; -- Get the user associated with the principal. function Get_User (From : in Principal) return AWA.Users.Models.User_Ref; -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none. function Get_User_Identifier (From : in Principal) return ADO.Identifier; -- Get the connection session used by the user. function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref; -- Get the connection session identifier used by the user. function Get_Session_Identifier (From : in Principal) return ADO.Identifier; -- Create a principal for the given user. function Create (User : in AWA.Users.Models.User_Ref; Session : in AWA.Users.Models.Session_Ref) return Principal_Access; -- Utility functions based on the security principal access type. -- Get the current user identifier invoking the service operation. -- Returns NO_IDENTIFIER if there is none or if the principal is not an AWA principal. function Get_User_Identifier (From : in ASF.Principals.Principal_Access) return ADO.Identifier; private type Principal is new ASF.Principals.Principal with record User : AWA.Users.Models.User_Ref; Session : AWA.Users.Models.Session_Ref; Roles : Security.Permissions.Role_Map; end record; end AWA.Users.Principals;
Use ASF Principal definitions
Use ASF Principal definitions
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
60f5dc3e4b15c6849043f552b1e99d9a60112040
src/sys/encoders/util-encoders-aes.ads
src/sys/encoders/util-encoders-aes.ads
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Interfaces; private with Ada.Finalization; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is use type Ada.Streams.Stream_Element_Offset; type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32; procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array) with Pre => Data'Length = 16 or Data'Length = 24 or Data'Length = 32; procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Decrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); type Cipher is tagged limited private; -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (E : in out Cipher; IV : in Word_Block_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Cipher and Util.Encoders.Transformer with private; -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) with Pre => Into'Length >= Block_Type'Length, Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length; -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Decoder is new Cipher and Util.Encoders.Transformer with private; -- Set the decryption key to use. procedure Set_Key (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Decoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset); private use Interfaces; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key; Rounds : Natural := 0; end record; type Cipher is limited new Ada.Finalization.Limited_Controlled with record IV : Word_Block_Type; Key : Key_Type; Mode : AES_Mode := CBC; Data_Count : Ada.Streams.Stream_Element_Offset := 0; Data : Block_Type; end record; overriding procedure Finalize (Object : in out Cipher); type Encoder is new Cipher and Util.Encoders.Transformer with null record; type Decoder is new Cipher and Util.Encoders.Transformer with null record; end Util.Encoders.AES;
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Interfaces; private with Ada.Finalization; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is use type Ada.Streams.Stream_Element_Offset; type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16); subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24); subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32); type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32; procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array) with Pre => Data'Length = 16 or Data'Length = 24 or Data'Length = 32; procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Ada.Streams.Stream_Element_Array); procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Decrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); type Cipher is tagged limited private; -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (E : in out Cipher; IV : in Word_Block_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Cipher and Util.Encoders.Transformer with private; -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) with Pre => Into'Length >= Block_Type'Length, Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length; -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Decoder is new Cipher and Util.Encoders.Transformer with private; -- Set the decryption key to use. procedure Set_Key (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Decoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset); private use Interfaces; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key := (others => 0); Rounds : Natural := 0; end record; type Cipher is limited new Ada.Finalization.Limited_Controlled with record IV : Word_Block_Type; Key : Key_Type; Mode : AES_Mode := CBC; Data_Count : Ada.Streams.Stream_Element_Offset := 0; Data : Block_Type; end record; overriding procedure Finalize (Object : in out Cipher); type Encoder is new Cipher and Util.Encoders.Transformer with null record; type Decoder is new Cipher and Util.Encoders.Transformer with null record; end Util.Encoders.AES;
Declare AES_128_Key, AES_192_Key, AES_256_Key types
Declare AES_128_Key, AES_192_Key, AES_256_Key types
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
87bacaff1d528ad80843d692b5a0c2fb7335f62f
src/sqlite/ado-drivers-connections-sqlite.ads
src/sqlite/ado-drivers-connections-sqlite.ads
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with Interfaces.C; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; package ADO.Drivers.Connections.Sqlite is subtype Sqlite3 is Sqlite3_H.sqlite3; -- The database connection manager type Sqlite_Driver is limited private; -- Initialize the SQLite driver. procedure Initialize; private -- Database connection implementation type Database_Connection is new ADO.Drivers.Connections.Database_Connection with record Server : aliased access Sqlite3_H.sqlite3; Name : Unbounded_String; end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver which manages this connection. overriding function Get_Driver (Database : in Database_Connection) return Driver_Access; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access; -- Create a delete statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- Create an insert statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- Create an update statement. overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- Start a transaction. overriding procedure Begin_Transaction (Database : in out Database_Connection); -- Commit the current transaction. overriding procedure Commit (Database : in out Database_Connection); -- Rollback the current transaction. overriding procedure Rollback (Database : in out Database_Connection); -- Load the database schema definition for the current database. overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition); -- Create the database and initialize it with the schema SQL file. overriding procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector); -- Closes the database connection overriding procedure Close (Database : in out Database_Connection); -- Releases the sqlite connection if it is open overriding procedure Finalize (Database : in out Database_Connection); type Sqlite_Driver is new ADO.Drivers.Connections.Driver with null record; -- Create a new SQLite connection using the configuration parameters. overriding procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class); end ADO.Drivers.Connections.Sqlite;
Declare the Create_Database procedure
Declare the Create_Database procedure
Ada
apache-2.0
stcarrez/ada-ado
866585d8d8579acd93c8a3a1e13a5b1145f64edf
src/natools-web-backends-filesystem.adb
src/natools-web-backends-filesystem.adb
------------------------------------------------------------------------------ -- Copyright (c) 2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Directories; with Ada.Streams.Stream_IO; with Natools.File_Streams; with Natools.S_Expressions.Atom_Ref_Constructors; package body Natools.Web.Backends.Filesystem is package Stream_IO renames Ada.Streams.Stream_IO; function Compose (Self : File_Backend; Directory, Name : S_Expressions.Atom) return String; ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Compose (Self : File_Backend; Directory, Name : S_Expressions.Atom) return String is begin return Ada.Directories.Compose (S_Expressions.To_String (Self.Root.Query) & S_Expressions.To_String (Directory), S_Expressions.To_String (Name)); end Compose; ---------------------- -- Public Interface -- ---------------------- overriding function Append (Self : in out File_Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is begin return File_Streams.Open (Stream_IO.Append_File, Compose (Self, Directory, Name)); end Append; not overriding function Create (Root : in String) return File_Backend is begin return (Root => S_Expressions.Atom_Ref_Constructors.Create (S_Expressions.To_Atom (Root))); end Create; function Create (Arguments : in out S_Expressions.Lockable.Descriptor'Class) return Backend'Class is begin case Arguments.Current_Event is when S_Expressions.Events.Add_Atom => return File_Backend' (Root => S_Expressions.Atom_Ref_Constructors.Create (Arguments.Current_Atom)); when others => raise Constraint_Error with "File_System backend expects an atom"; end case; end Create; overriding function Create (Self : in out File_Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is begin return File_Streams.Create (Stream_IO.Append_File, Compose (Self, Directory, Name)); end Create; overriding procedure Delete (Self : in out File_Backend; Directory, Name : in S_Expressions.Atom) is begin Ada.Directories.Delete_File (Compose (Self, Directory, Name)); end Delete; overriding procedure Iterate (Self : in File_Backend; Directory : in S_Expressions.Atom; Process : not null access procedure (Name : in S_Expressions.Atom)) is Search : Ada.Directories.Search_Type; Directory_Entry : Ada.Directories.Directory_Entry_Type; begin Ada.Directories.Start_Search (Search => Search, Directory => S_Expressions.To_String (Self.Root.Query) & S_Expressions.To_String (Directory), Pattern => "", Filter => (Ada.Directories.Ordinary_File => True, others => False)); while Ada.Directories.More_Entries (Search) loop Ada.Directories.Get_Next_Entry (Search, Directory_Entry); Process.all (S_Expressions.To_Atom (Ada.Directories.Simple_Name (Directory_Entry))); end loop; Ada.Directories.End_Search (Search); end Iterate; overriding function Overwrite (Self : in out File_Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is begin return File_Streams.Open (Stream_IO.Out_File, Compose (Self, Directory, Name)); end Overwrite; overriding function Read (Self : in File_Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is begin return File_Streams.Open (Stream_IO.In_File, Compose (Self, Directory, Name)); end Read; end Natools.Web.Backends.Filesystem;
------------------------------------------------------------------------------ -- Copyright (c) 2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Directories; with Ada.Streams.Stream_IO; with Natools.File_Streams; with Natools.S_Expressions.Atom_Ref_Constructors; package body Natools.Web.Backends.Filesystem is package Stream_IO renames Ada.Streams.Stream_IO; function Compose (Self : File_Backend; Directory, Name : S_Expressions.Atom) return String; ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Compose (Self : File_Backend; Directory, Name : S_Expressions.Atom) return String is begin return Ada.Directories.Compose (S_Expressions.To_String (Self.Root.Query) & S_Expressions.To_String (Directory), S_Expressions.To_String (Name)); end Compose; ---------------------- -- Public Interface -- ---------------------- overriding function Append (Self : in out File_Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is begin return File_Streams.Open (Stream_IO.Append_File, Compose (Self, Directory, Name)); end Append; not overriding function Create (Root : in String) return File_Backend is begin return (Root => S_Expressions.Atom_Ref_Constructors.Create (S_Expressions.To_Atom (Root))); end Create; function Create (Arguments : in out S_Expressions.Lockable.Descriptor'Class) return Backend'Class is begin case Arguments.Current_Event is when S_Expressions.Events.Add_Atom => return File_Backend' (Root => S_Expressions.Atom_Ref_Constructors.Create (Arguments.Current_Atom)); when others => raise Constraint_Error with "File_System backend expects an atom"; end case; end Create; overriding function Create (Self : in out File_Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is begin Ada.Directories.Create_Path (S_Expressions.To_String (Self.Root.Query) & S_Expressions.To_String (Directory)); return File_Streams.Create (Stream_IO.Append_File, Compose (Self, Directory, Name)); end Create; overriding procedure Delete (Self : in out File_Backend; Directory, Name : in S_Expressions.Atom) is begin Ada.Directories.Delete_File (Compose (Self, Directory, Name)); end Delete; overriding procedure Iterate (Self : in File_Backend; Directory : in S_Expressions.Atom; Process : not null access procedure (Name : in S_Expressions.Atom)) is Search : Ada.Directories.Search_Type; Directory_Entry : Ada.Directories.Directory_Entry_Type; begin Ada.Directories.Start_Search (Search => Search, Directory => S_Expressions.To_String (Self.Root.Query) & S_Expressions.To_String (Directory), Pattern => "", Filter => (Ada.Directories.Ordinary_File => True, others => False)); while Ada.Directories.More_Entries (Search) loop Ada.Directories.Get_Next_Entry (Search, Directory_Entry); Process.all (S_Expressions.To_Atom (Ada.Directories.Simple_Name (Directory_Entry))); end loop; Ada.Directories.End_Search (Search); end Iterate; overriding function Overwrite (Self : in out File_Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is begin return File_Streams.Open (Stream_IO.Out_File, Compose (Self, Directory, Name)); end Overwrite; overriding function Read (Self : in File_Backend; Directory, Name : in S_Expressions.Atom) return Ada.Streams.Root_Stream_Type'Class is begin return File_Streams.Open (Stream_IO.In_File, Compose (Self, Directory, Name)); end Read; end Natools.Web.Backends.Filesystem;
create the containing directory when creating a file
backends-filesystem: create the containing directory when creating a file
Ada
isc
faelys/natools-web,faelys/natools-web
759ceaeb945b5ab74bcb6df23386514deaedf89a
lua.ads
lua.ads
-- Lua -- an Ada 2012 interface to Lua -- Copyright (c) 2015, James Humphry -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. with Ada.Finalization; private with System; private with Interfaces.C; package Lua is -- Types used by Lua subtype Lua_Number is Long_Float; subtype Lua_Integer is Long_Long_Integer; -- Enumerations type Thread_Status is (OK, YIELD, ERRRUN, ERRSYNTAX, ERRMEM, ERRGCMM, ERRERR); type Arith_Op is (OPADD, OPSUB, OPMUL, OPMOD, OPPOW, OPDIV, OPIDIV, OPBAND, OPBOR, OPBXOR, OPSHL, OPSHR, OPUNM, OPBNOT); type Comparison_Op is (OPEQ, OPLT, OPLE); type GC_Inputs is (GCSTOP, GCRESTART, GCCOLLECT, GCCOUNT, GCCOUNTB, GCSTEP, GCSETPAUSE, GCSETSTEPMUL, GCISRUNNING); for GC_Inputs use (GCSTOP => 0, GCRESTART => 1, GCCOLLECT => 2, GCCOUNT => 3, GCCOUNTB => 4, GCSTEP => 5, GCSETPAUSE => 6, GCSETSTEPMUL => 7, GCISRUNNING => 9); subtype GC_Op is GC_Inputs range GCSTOP..GCSTEP; subtype GC_Param is GC_Inputs range GCSETPAUSE..GCSETSTEPMUL; subtype GC_Queries is GC_Inputs range GCISRUNNING..GCISRUNNING; type Lua_Type is (TNONE, TNIL, TBOOLEAN, TLIGHTUSERDATA, TNUMBER, TSTRING, TTABLE, TFUNCTION, TUSERDATA, TTHREAD, TNUMTAGS); type Lua_ChunkMode is (Binary, Text, Binary_and_Text); -- Exceptions -- Lua_Error is raised whenever there is a violation of a constraint -- imposed by the semantics of the Lua interface - for example, trying to -- retrieve a number from a non-numeric value on the stack or using a -- reference on a different Lua_State than it was created on. Lua_Error : exception; -- Special stack positions and the registry MaxStack : constant Integer with Import, Convention => C, Link_Name => "lua_conf_luai_maxstack"; RegistryIndex : constant Integer with Import, Convention => C, Link_Name => "lua_conf_registry_index"; RIDX_MainThread : constant Integer; RIDX_Globals : constant Integer; RIDX_Last : constant Integer; function UpvalueIndex (i : in Integer) return Integer; -- Basic state control type Lua_State is tagged limited private; type Lua_Thread; function Version (L : in Lua_State) return Long_Float; function Status (L : in Lua_State) return Thread_Status; function LoadString (L : in Lua_State; S : in String) return Thread_Status; function LoadFile (L : in Lua_State; Name : in String; Mode : in Lua_ChunkMode := Binary_and_Text) return Thread_Status; -- Calling, yielding and functions procedure Call (L : in Lua_State; nargs : in Integer; nresults : in Integer) with Inline, Pre => IsFunction(L, -nargs-1); procedure Call_Function (L : in Lua_State; name : in String; nargs : in Integer; nresults : in Integer); function PCall (L : in Lua_State; nargs : in Integer; nresults : in Integer; msgh : in Integer := 0) return Thread_Status with Inline, Pre => IsFunction(L, -nargs-1); function PCall_Function (L : in Lua_State; name : in String; nargs : in Integer; nresults : in Integer; msgh : in Integer := 0) return Thread_Status; type AdaFunction is access function (L : Lua_State'Class) return Natural; procedure Register(L : in Lua_State; name : in String; f : in AdaFunction); MultRet_Sentinel : constant Integer with Import, Convention => C, Link_Name => "lua_conf_multret"; -- Pushing values to the stack procedure PushAdaClosure (L : in Lua_State; f : in AdaFunction; n : in Natural); procedure PushAdaFunction (L : in Lua_State; f : in AdaFunction); procedure PushBoolean (L : in Lua_State; b : in Boolean); procedure PushInteger (L : in Lua_State; n : in Lua_Integer); procedure PushNil (L : in Lua_State); procedure PushNumber (L : in Lua_State; n : in Lua_Number); procedure PushString (L : in Lua_State; s : in String); function PushThread (L : in Lua_State) return Boolean; procedure PushThread (L : in Lua_State); function StringToNumber (L : in Lua_State; s : in String) return Boolean; -- Pulling values from the stack function ToAdaFunction (L : in Lua_State; index : in Integer) return AdaFunction; function ToBoolean (L : in Lua_State; index : in Integer) return Boolean; function ToInteger (L : in Lua_State; index : in Integer) return Lua_Integer; function ToNumber (L : in Lua_State; index : in Integer) return Lua_Number; function ToString (L : in Lua_State; index : in Integer) return String; function ToThread (L : in Lua_State; index : in Integer) return Lua_Thread; -- Operations on values procedure Arith (L : in Lua_State; op : in Arith_Op); function Compare (L : in Lua_State; index1 : in Integer; index2 : in Integer; op : in Comparison_Op) return Boolean; procedure Len (L : in Lua_State; index : Integer); function RawEqual (L : in Lua_State; index1, index2 : in Integer) return Boolean; function RawLen (L : in Lua_State; index : Integer) return Integer; -- Garbage Collector control procedure GC (L : in Lua_State; what : in GC_Op); function GC (L : in Lua_State; what : in GC_Param; data : in Integer) return Integer; function GC (L : in Lua_State) return Boolean; -- Stack manipulation and information function AbsIndex (L : in Lua_State; idx : in Integer) return Integer; function CheckStack (L : in Lua_State; n : in Integer) return Boolean; procedure Copy (L : in Lua_State; fromidx : in Integer; toidx : in Integer); function GetTop (L : in Lua_State) return Integer; procedure Insert (L : in Lua_State; index : in Integer); procedure Pop (L : in Lua_State; n : in Integer); procedure PushValue (L : in Lua_State; index : in Integer); procedure Remove (L : in Lua_State; index : in Integer); procedure Replace (L : in Lua_State; index : in Integer); procedure Rotate (L : in Lua_State; idx : in Integer; n : in Integer); procedure SetTop (L : in Lua_State; index : in Integer); -- Type information function IsAdaFunction (L : in Lua_State; index : in Integer) return Boolean; function IsBoolean (L : in Lua_State; index : in Integer) return Boolean; function IsCFunction (L : in Lua_State; index : in Integer) return Boolean; function IsFunction (L : in Lua_State; index : in Integer) return Boolean; function IsInteger (L : in Lua_State; index : in Integer) return Boolean; function IsLightuserdata (L : in Lua_State; index : in Integer) return Boolean; function IsNil (L : in Lua_State; index : in Integer) return Boolean; function IsNone (L : in Lua_State; index : in Integer) return Boolean; function IsNoneOrNil (L : in Lua_State; index : in Integer) return Boolean; function IsNumber (L : in Lua_State; index : in Integer) return Boolean; function IsString (L : in Lua_State; index : in Integer) return Boolean; function IsTable (L : in Lua_State; index : in Integer) return Boolean; function IsThread (L : in Lua_State; index : in Integer) return Boolean; function IsUserdata (L : in Lua_State; index : in Integer) return Boolean; function TypeInfo (L : in Lua_State; index : in Integer) return Lua_Type; function TypeName (L : in Lua_State; tp : in Lua_Type) return String; function TypeName (L : in Lua_State; index : in Integer) return String is (TypeName(L, Typeinfo(L, index))); function Userdata_Name (L : in Lua_State; index : in Integer) return String; -- Table manipulation procedure CreateTable (L : in Lua_State; narr : in Integer := 0; nrec : in Integer := 0); procedure NewTable (L : in Lua_State); function GetField (L : in Lua_State; index : in Integer; k : in String) return Lua_Type with Inline, Pre => IsTable(L, index); procedure GetField (L : in Lua_State; index : in Integer; k : in String) with Inline, Pre => IsTable(L, index); function Geti (L : in Lua_State; index : in Integer; i : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure Geti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); function GetTable (L : in Lua_State; index : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure GetTable (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); function Next (L : in Lua_State; index : in Integer) return Boolean; function RawGet (L : in Lua_State; index : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure RawGet (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); function RawGeti (L : in Lua_State; index : in Integer; i : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure RawGeti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure RawSet (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); procedure RawSeti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure SetField (L : in Lua_State; index : in Integer; k : in String) with Inline, Pre => IsTable(L, index); procedure Seti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure SetTable (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); -- Globals and metatables function GetGlobal (L : in Lua_State; name : in String) return Lua_Type; procedure GetGlobal (L : in Lua_State; name : in String); function GetMetatable (L : in Lua_State; index : in Integer) return Boolean; procedure GetMetatable (L : in Lua_State; index : in Integer); procedure PushGlobalTable (L : in Lua_State); procedure SetGlobal (L : in Lua_State; name : in String); procedure SetMetatable (L : in Lua_State; index : in Integer); -- Threads type Lua_Thread is new Lua_State with private; function IsYieldable (L : in Lua_State'Class) return Boolean; function NewThread (L : in Lua_State'Class) return Lua_Thread; function Resume(L : in Lua_State'Class; from : in Lua_State'Class; nargs : Integer) return Thread_Status; procedure XMove (from, to : in Lua_Thread; n : in Integer); procedure Yield (L : in Lua_State; nresults : Integer); -- References type Lua_Reference is tagged private; function Ref (L : in Lua_State'Class; t : in Integer := RegistryIndex) return Lua_Reference; function Get (L : in Lua_State; R : Lua_Reference'Class) return Lua_Type; procedure Get (L : in Lua_State; R : Lua_Reference'Class); private subtype void_ptr is System.Address; for Thread_Status use (OK => 0, YIELD => 1, ERRRUN => 2, ERRSYNTAX => 3, ERRMEM => 4, ERRGCMM => 5, ERRERR => 6); for Arith_Op use (OPADD => 0, OPSUB => 1, OPMUL => 2, OPMOD => 3, OPPOW => 4, OPDIV => 5, OPIDIV => 6, OPBAND => 7, OPBOR => 8, OPBXOR => 9, OPSHL => 10, OPSHR => 11, OPUNM => 12, OPBNOT => 13); for Comparison_Op use (OPEQ => 0, OPLT => 1, OPLE => 2); for Lua_Type use (TNONE => -1, TNIL => 0, TBOOLEAN => 1, TLIGHTUSERDATA => 2, TNUMBER => 3, TSTRING => 4, TTABLE => 5, TFUNCTION => 6, TUSERDATA => 7, TTHREAD => 8, TNUMTAGS => 9); RIDX_MainThread : constant Integer := 1; RIDX_Globals : constant Integer := 2; RIDX_Last : constant Integer := RIDX_Globals; type Lua_State is new Ada.Finalization.Limited_Controlled with record L : void_Ptr; end record; overriding procedure Initialize (Object : in out Lua_State); overriding procedure Finalize (Object : in out Lua_State); -- Existing_State is a clone of State but without automatic initialization -- It is used internally when lua_State* are returned from the Lua library -- and we don't want to re-initialize them when turning them into the -- State record type. type Existing_State is new Lua_State with null record; overriding procedure Initialize (Object : in out Existing_State) is null; overriding procedure Finalize (Object : in out Existing_State) is null; type Lua_Thread is new Existing_State with null record; -- Trampolines function CFunction_Trampoline (L : System.Address) return Interfaces.C.int with Convention => C; -- References type Lua_Reference_Value is record State : void_Ptr; Table : Interfaces.C.Int; Ref : Interfaces.C.Int; Count : Natural := 0; end record; type Lua_Reference_Value_Access is access Lua_Reference_Value; type Lua_Reference is new Ada.Finalization.Controlled with record E : Lua_Reference_Value_Access := null; end record; overriding procedure Initialize (Object : in out Lua_Reference) is null; overriding procedure Adjust (Object : in out Lua_Reference); overriding procedure Finalize (Object : in out Lua_Reference); end Lua;
-- Lua -- an Ada 2012 interface to Lua -- Copyright (c) 2015, James Humphry -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. with Ada.Finalization; private with System; private with Interfaces.C; package Lua is -- Types used by Lua subtype Lua_Number is Long_Float; subtype Lua_Integer is Long_Long_Integer; -- Enumerations type Thread_Status is (OK, YIELD, ERRRUN, ERRSYNTAX, ERRMEM, ERRGCMM, ERRERR, ERRFILE); type Arith_Op is (OPADD, OPSUB, OPMUL, OPMOD, OPPOW, OPDIV, OPIDIV, OPBAND, OPBOR, OPBXOR, OPSHL, OPSHR, OPUNM, OPBNOT); type Comparison_Op is (OPEQ, OPLT, OPLE); type GC_Inputs is (GCSTOP, GCRESTART, GCCOLLECT, GCCOUNT, GCCOUNTB, GCSTEP, GCSETPAUSE, GCSETSTEPMUL, GCISRUNNING); for GC_Inputs use (GCSTOP => 0, GCRESTART => 1, GCCOLLECT => 2, GCCOUNT => 3, GCCOUNTB => 4, GCSTEP => 5, GCSETPAUSE => 6, GCSETSTEPMUL => 7, GCISRUNNING => 9); subtype GC_Op is GC_Inputs range GCSTOP..GCSTEP; subtype GC_Param is GC_Inputs range GCSETPAUSE..GCSETSTEPMUL; subtype GC_Queries is GC_Inputs range GCISRUNNING..GCISRUNNING; type Lua_Type is (TNONE, TNIL, TBOOLEAN, TLIGHTUSERDATA, TNUMBER, TSTRING, TTABLE, TFUNCTION, TUSERDATA, TTHREAD, TNUMTAGS); type Lua_ChunkMode is (Binary, Text, Binary_and_Text); -- Exceptions -- Lua_Error is raised whenever there is a violation of a constraint -- imposed by the semantics of the Lua interface - for example, trying to -- retrieve a number from a non-numeric value on the stack or using a -- reference on a different Lua_State than it was created on. Lua_Error : exception; -- Special stack positions and the registry MaxStack : constant Integer with Import, Convention => C, Link_Name => "lua_conf_luai_maxstack"; RegistryIndex : constant Integer with Import, Convention => C, Link_Name => "lua_conf_registry_index"; RIDX_MainThread : constant Integer; RIDX_Globals : constant Integer; RIDX_Last : constant Integer; function UpvalueIndex (i : in Integer) return Integer; -- Basic state control type Lua_State is tagged limited private; type Lua_Thread; function Version (L : in Lua_State) return Long_Float; function Status (L : in Lua_State) return Thread_Status; function LoadString (L : in Lua_State; S : in String) return Thread_Status; function LoadFile (L : in Lua_State; Name : in String; Mode : in Lua_ChunkMode := Binary_and_Text) return Thread_Status; -- Calling, yielding and functions procedure Call (L : in Lua_State; nargs : in Integer; nresults : in Integer) with Inline, Pre => IsFunction(L, -nargs-1); procedure Call_Function (L : in Lua_State; name : in String; nargs : in Integer; nresults : in Integer); function PCall (L : in Lua_State; nargs : in Integer; nresults : in Integer; msgh : in Integer := 0) return Thread_Status with Inline, Pre => IsFunction(L, -nargs-1); function PCall_Function (L : in Lua_State; name : in String; nargs : in Integer; nresults : in Integer; msgh : in Integer := 0) return Thread_Status; type AdaFunction is access function (L : Lua_State'Class) return Natural; procedure Register(L : in Lua_State; name : in String; f : in AdaFunction); MultRet_Sentinel : constant Integer with Import, Convention => C, Link_Name => "lua_conf_multret"; -- Pushing values to the stack procedure PushAdaClosure (L : in Lua_State; f : in AdaFunction; n : in Natural); procedure PushAdaFunction (L : in Lua_State; f : in AdaFunction); procedure PushBoolean (L : in Lua_State; b : in Boolean); procedure PushInteger (L : in Lua_State; n : in Lua_Integer); procedure PushNil (L : in Lua_State); procedure PushNumber (L : in Lua_State; n : in Lua_Number); procedure PushString (L : in Lua_State; s : in String); function PushThread (L : in Lua_State) return Boolean; procedure PushThread (L : in Lua_State); function StringToNumber (L : in Lua_State; s : in String) return Boolean; -- Pulling values from the stack function ToAdaFunction (L : in Lua_State; index : in Integer) return AdaFunction; function ToBoolean (L : in Lua_State; index : in Integer) return Boolean; function ToInteger (L : in Lua_State; index : in Integer) return Lua_Integer; function ToNumber (L : in Lua_State; index : in Integer) return Lua_Number; function ToString (L : in Lua_State; index : in Integer) return String; function ToThread (L : in Lua_State; index : in Integer) return Lua_Thread; -- Operations on values procedure Arith (L : in Lua_State; op : in Arith_Op); function Compare (L : in Lua_State; index1 : in Integer; index2 : in Integer; op : in Comparison_Op) return Boolean; procedure Len (L : in Lua_State; index : Integer); function RawEqual (L : in Lua_State; index1, index2 : in Integer) return Boolean; function RawLen (L : in Lua_State; index : Integer) return Integer; -- Garbage Collector control procedure GC (L : in Lua_State; what : in GC_Op); function GC (L : in Lua_State; what : in GC_Param; data : in Integer) return Integer; function GC (L : in Lua_State) return Boolean; -- Stack manipulation and information function AbsIndex (L : in Lua_State; idx : in Integer) return Integer; function CheckStack (L : in Lua_State; n : in Integer) return Boolean; procedure Copy (L : in Lua_State; fromidx : in Integer; toidx : in Integer); function GetTop (L : in Lua_State) return Integer; procedure Insert (L : in Lua_State; index : in Integer); procedure Pop (L : in Lua_State; n : in Integer); procedure PushValue (L : in Lua_State; index : in Integer); procedure Remove (L : in Lua_State; index : in Integer); procedure Replace (L : in Lua_State; index : in Integer); procedure Rotate (L : in Lua_State; idx : in Integer; n : in Integer); procedure SetTop (L : in Lua_State; index : in Integer); -- Type information function IsAdaFunction (L : in Lua_State; index : in Integer) return Boolean; function IsBoolean (L : in Lua_State; index : in Integer) return Boolean; function IsCFunction (L : in Lua_State; index : in Integer) return Boolean; function IsFunction (L : in Lua_State; index : in Integer) return Boolean; function IsInteger (L : in Lua_State; index : in Integer) return Boolean; function IsLightuserdata (L : in Lua_State; index : in Integer) return Boolean; function IsNil (L : in Lua_State; index : in Integer) return Boolean; function IsNone (L : in Lua_State; index : in Integer) return Boolean; function IsNoneOrNil (L : in Lua_State; index : in Integer) return Boolean; function IsNumber (L : in Lua_State; index : in Integer) return Boolean; function IsString (L : in Lua_State; index : in Integer) return Boolean; function IsTable (L : in Lua_State; index : in Integer) return Boolean; function IsThread (L : in Lua_State; index : in Integer) return Boolean; function IsUserdata (L : in Lua_State; index : in Integer) return Boolean; function TypeInfo (L : in Lua_State; index : in Integer) return Lua_Type; function TypeName (L : in Lua_State; tp : in Lua_Type) return String; function TypeName (L : in Lua_State; index : in Integer) return String is (TypeName(L, Typeinfo(L, index))); function Userdata_Name (L : in Lua_State; index : in Integer) return String; -- Table manipulation procedure CreateTable (L : in Lua_State; narr : in Integer := 0; nrec : in Integer := 0); procedure NewTable (L : in Lua_State); function GetField (L : in Lua_State; index : in Integer; k : in String) return Lua_Type with Inline, Pre => IsTable(L, index); procedure GetField (L : in Lua_State; index : in Integer; k : in String) with Inline, Pre => IsTable(L, index); function Geti (L : in Lua_State; index : in Integer; i : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure Geti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); function GetTable (L : in Lua_State; index : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure GetTable (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); function Next (L : in Lua_State; index : in Integer) return Boolean; function RawGet (L : in Lua_State; index : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure RawGet (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); function RawGeti (L : in Lua_State; index : in Integer; i : in Integer) return Lua_Type with Inline, Pre => IsTable(L, index); procedure RawGeti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure RawSet (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); procedure RawSeti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure SetField (L : in Lua_State; index : in Integer; k : in String) with Inline, Pre => IsTable(L, index); procedure Seti (L : in Lua_State; index : in Integer; i : in Integer) with Inline, Pre => IsTable(L, index); procedure SetTable (L : in Lua_State; index : in Integer) with Inline, Pre => IsTable(L, index); -- Globals and metatables function GetGlobal (L : in Lua_State; name : in String) return Lua_Type; procedure GetGlobal (L : in Lua_State; name : in String); function GetMetatable (L : in Lua_State; index : in Integer) return Boolean; procedure GetMetatable (L : in Lua_State; index : in Integer); procedure PushGlobalTable (L : in Lua_State); procedure SetGlobal (L : in Lua_State; name : in String); procedure SetMetatable (L : in Lua_State; index : in Integer); -- Threads type Lua_Thread is new Lua_State with private; function IsYieldable (L : in Lua_State'Class) return Boolean; function NewThread (L : in Lua_State'Class) return Lua_Thread; function Resume(L : in Lua_State'Class; from : in Lua_State'Class; nargs : Integer) return Thread_Status; procedure XMove (from, to : in Lua_Thread; n : in Integer); procedure Yield (L : in Lua_State; nresults : Integer); -- References type Lua_Reference is tagged private; function Ref (L : in Lua_State'Class; t : in Integer := RegistryIndex) return Lua_Reference; function Get (L : in Lua_State; R : Lua_Reference'Class) return Lua_Type; procedure Get (L : in Lua_State; R : Lua_Reference'Class); private subtype void_ptr is System.Address; for Thread_Status use (OK => 0, YIELD => 1, ERRRUN => 2, ERRSYNTAX => 3, ERRMEM => 4, ERRGCMM => 5, ERRERR => 6, ERRFILE => 7); for Arith_Op use (OPADD => 0, OPSUB => 1, OPMUL => 2, OPMOD => 3, OPPOW => 4, OPDIV => 5, OPIDIV => 6, OPBAND => 7, OPBOR => 8, OPBXOR => 9, OPSHL => 10, OPSHR => 11, OPUNM => 12, OPBNOT => 13); for Comparison_Op use (OPEQ => 0, OPLT => 1, OPLE => 2); for Lua_Type use (TNONE => -1, TNIL => 0, TBOOLEAN => 1, TLIGHTUSERDATA => 2, TNUMBER => 3, TSTRING => 4, TTABLE => 5, TFUNCTION => 6, TUSERDATA => 7, TTHREAD => 8, TNUMTAGS => 9); RIDX_MainThread : constant Integer := 1; RIDX_Globals : constant Integer := 2; RIDX_Last : constant Integer := RIDX_Globals; type Lua_State is new Ada.Finalization.Limited_Controlled with record L : void_Ptr; end record; overriding procedure Initialize (Object : in out Lua_State); overriding procedure Finalize (Object : in out Lua_State); -- Existing_State is a clone of State but without automatic initialization -- It is used internally when lua_State* are returned from the Lua library -- and we don't want to re-initialize them when turning them into the -- State record type. type Existing_State is new Lua_State with null record; overriding procedure Initialize (Object : in out Existing_State) is null; overriding procedure Finalize (Object : in out Existing_State) is null; type Lua_Thread is new Existing_State with null record; -- Trampolines function CFunction_Trampoline (L : System.Address) return Interfaces.C.int with Convention => C; -- References type Lua_Reference_Value is record State : void_Ptr; Table : Interfaces.C.Int; Ref : Interfaces.C.Int; Count : Natural := 0; end record; type Lua_Reference_Value_Access is access Lua_Reference_Value; type Lua_Reference is new Ada.Finalization.Controlled with record E : Lua_Reference_Value_Access := null; end record; overriding procedure Initialize (Object : in out Lua_Reference) is null; overriding procedure Adjust (Object : in out Lua_Reference); overriding procedure Finalize (Object : in out Lua_Reference); end Lua;
Include ERRFILE in Thread_Status enumeration
Include ERRFILE in Thread_Status enumeration
Ada
mit
jhumphry/aLua
067cefba1b151973987783db0237f68f44fa6fe3
awa/src/awa-applications-configs.adb
awa/src/awa-applications-configs.adb
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012, 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.Command_Line; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Files; with Util.Log.Loggers; with Util.Serialize.IO.XML; with ASF.Contexts.Faces; with ASF.Applications.Main.Configs; with Security.Policies; with AWA.Events.Configs; with AWA.Services.Contexts; package body AWA.Applications.Configs is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- 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. -- ------------------------------ package body Reader_Config is App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access; package Bean_Config is new ASF.Applications.Main.Configs.Reader_Config (Mapper, App_Access, Context.all'Access, Override_Context); package Event_Config is new AWA.Events.Configs.Reader_Config (Mapper => Mapper, Manager => App.Events'Unchecked_Access, Context => Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Event_Config); 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) is Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Ctx : AWA.Services.Contexts.Service_Context; Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; begin Log.Info ("Reading application configuration file {0}", File); Ctx.Set_Context (App'Unchecked_Access, null); declare package Config is new Reader_Config (Mapper, App'Unchecked_Access, Context, Override_Context); pragma Warnings (Off, Config); begin Sec.Prepare_Config (Mapper); -- Initialize the parser with the module configuration mappers (if any). Initialize_Parser (App, Reader); if Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.Mappers.Dump (Mapper, Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File, Mapper); end; exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; -- ------------------------------ -- Get the configuration path for the application name. -- The configuration path is search from: -- o the current directory, -- o the 'config' directory, -- o the Dynamo installation directory in share/dynamo -- ------------------------------ function Get_Config_Path (Name : in String) return String is use Ada.Strings.Unbounded; use Ada.Directories; Command : constant String := Ada.Command_Line.Command_Name; Path : constant String := Ada.Directories.Containing_Directory (Command); Dir : constant String := Containing_Directory (Path); Paths : Ada.Strings.Unbounded.Unbounded_String; begin Append (Paths, ".;"); Append (Paths, Util.Files.Compose (Dir, "config")); Append (Paths, ";"); Append (Paths, Util.Files.Compose (Dir, "share/dynamo/" & Name)); return Util.Files.Find_File_Path (Name & ".properties", To_String (Paths)); end Get_Config_Path; end AWA.Applications.Configs;
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 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.Command_Line; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Files; with Util.Log.Loggers; with Util.Serialize.IO.XML; with ASF.Contexts.Faces; with ASF.Applications.Main.Configs; with Security.Policies; with AWA.Events.Configs.Reader_Config; with AWA.Services.Contexts; package body AWA.Applications.Configs is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications.Configs"); -- ------------------------------ -- 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. -- ------------------------------ package body Reader_Config is App_Access : constant ASF.Contexts.Faces.Application_Access := App.all'Unchecked_Access; package Bean_Config is new ASF.Applications.Main.Configs.Reader_Config (Mapper, App_Access, Context.all'Access, Override_Context); package Event_Config is new AWA.Events.Configs.Reader_Config (Mapper => Mapper, Manager => App.Events'Unchecked_Access, Context => Context.all'Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Event_Config); begin Event_Config.Initialize; 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) is Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Ctx : AWA.Services.Contexts.Service_Context; Sec : constant Security.Policies.Policy_Manager_Access := App.Get_Security_Manager; begin Log.Info ("Reading application configuration file {0}", File); Ctx.Set_Context (App'Unchecked_Access, null); declare package Config is new Reader_Config (Mapper, App'Unchecked_Access, Context, Override_Context); pragma Warnings (Off, Config); begin Sec.Prepare_Config (Mapper); -- Initialize the parser with the module configuration mappers (if any). Initialize_Parser (App, Reader); if Log.Get_Level >= Util.Log.DEBUG_LEVEL then Util.Serialize.Mappers.Dump (Mapper, Log); end if; -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File, Mapper); end; exception when others => Log.Error ("Error while reading {0}", File); raise; end Read_Configuration; -- ------------------------------ -- Get the configuration path for the application name. -- The configuration path is search from: -- o the current directory, -- o the 'config' directory, -- o the Dynamo installation directory in share/dynamo -- ------------------------------ function Get_Config_Path (Name : in String) return String is use Ada.Strings.Unbounded; use Ada.Directories; Command : constant String := Ada.Command_Line.Command_Name; Path : constant String := Ada.Directories.Containing_Directory (Command); Dir : constant String := Containing_Directory (Path); Paths : Ada.Strings.Unbounded.Unbounded_String; begin Append (Paths, ".;"); Append (Paths, Util.Files.Compose (Dir, "config")); Append (Paths, ";"); Append (Paths, Util.Files.Compose (Dir, "share/dynamo/" & Name)); return Util.Files.Find_File_Path (Name & ".properties", To_String (Paths)); end Get_Config_Path; end AWA.Applications.Configs;
Update to use the new Reader_Config package to read events configuration files
Update to use the new Reader_Config package to read events configuration files
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
616d99ff53d542d57d8d6b1add41373acc4f50b4
src/natools-smaz_generic-tools.ads
src/natools-smaz_generic-tools.ads
------------------------------------------------------------------------------ -- 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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Smaz_Generic.Tools provides tools specific to the dictionary -- -- implementation. These tools are useful for dictionary manipulation, -- -- even though the intended use of this Smaz implementation is through a -- -- global constant dictionary object. -- ------------------------------------------------------------------------------ with Ada.Containers; with Natools.Smaz_Tools; generic package Natools.Smaz_Generic.Tools is pragma Preelaborate; package String_Lists renames Smaz_Tools.String_Lists; function To_Dictionary (List : in String_Lists.List; Variable_Length_Verbatim : in Boolean) return Dictionary with Pre => String_Lists.Length (List) in 1 .. Ada.Containers.Count_Type (Ada.Streams.Stream_Element'Last); -- Build a Dictionary object from a string list -- Note that Hash is set to a placeholder which unconditionnally -- raises Program_Error when called. function To_String_List (Dict : in Dictionary) return String_Lists.List; -- Convert a dictionary back to the corresponding list of words generic with procedure Put_Line (Line : String); procedure Print_Dictionary_In_Ada (Dict : in Dictionary; Hash_Image : in String := "TODO"; Max_Width : in Positive := 70; First_Prefix : in String := " := ("; Prefix : in String := " "; Half_Indent : in String := " "); -- Output Ada code corresponding to the value of the dictionary. -- Note that Prefix is the actual base indentation, while Half_Indent -- is added beyond Prefix before values continued on another line. -- Frist_Prefix is used instead of Prefix on the first line. -- All the defaults value are what was used to generate the constant -- in Natools.Smaz_Original. function Remove_Element (Dict : in Dictionary; Index : in Dictionary_Code) return Dictionary with Pre => Index <= Dict.Last_Code, Post => Dict.Last_Code = Dictionary_Code'Succ (Remove_Element'Result.Last_Code) and then (Index = Dictionary_Code'First or else (for all I in Dictionary_Code'First .. Dictionary_Code'Pred (Index) => Dict_Entry (Dict, I) = Dict_Entry (Remove_Element'Result, I))) and then (Index = Dict.Last_Code or else (for all I in Index .. Dictionary_Code'Pred (Dict.Last_Code) => Dict_Entry (Dict, Dictionary_Code'Succ (I)) = Dict_Entry (Remove_Element'Result, I))); -- Return a new dictionary equal to Dict without element for Index function Append_String (Dict : in Dictionary; Value : in String) return Dictionary with Pre => Dict.Last_Code < Dictionary_Code'Last and then Value'Length > 0, Post => Dict.Last_Code = Dictionary_Code'Pred (Append_String'Result.Last_Code) and then (for all I in Dictionary_Code'First .. Dict.Last_Code => Dict_Entry (Dict, I) = Dict_Entry (Append_String'Result, I)) and then Dict_Entry (Append_String'Result, Append_String'Result.Last_Code) = Value; -- Return a new dictionary with Value appended type Dictionary_Counts is array (Dictionary_Code) of Smaz_Tools.String_Count; procedure Evaluate_Dictionary (Dict : in Dictionary; Corpus : in String_Lists.List; Compressed_Size : out Ada.Streams.Stream_Element_Count; Counts : out Dictionary_Counts); procedure Evaluate_Dictionary_Partial (Dict : in Dictionary; Corpus_Entry : in String; Compressed_Size : in out Ada.Streams.Stream_Element_Count; Counts : in out Dictionary_Counts); -- Compress all strings of Corpus, returning the total number of -- compressed bytes and the number of uses for each dictionary -- element. function Worst_Index (Dict : in Dictionary; Counts : in Dictionary_Counts; Method : in Smaz_Tools.Methods.Enum) return Dictionary_Code; -- Return the element with worst score function Score_Encoded (Dict : in Dictionary; Counts : in Dictionary_Counts; E : in Dictionary_Code) return Smaz_Tools.Score_Value is (Smaz_Tools.Score_Encoded (Counts (E), Dict_Entry_Length (Dict, E))); -- Score value using the amount of encoded data using E function Score_Frequency (Dict : in Dictionary; Counts : in Dictionary_Counts; E : in Dictionary_Code) return Smaz_Tools.Score_Value is (Smaz_Tools.Score_Frequency (Counts (E), Dict_Entry_Length (Dict, E))); -- Score value using the number of times E was used function Score_Gain (Dict : in Dictionary; Counts : in Dictionary_Counts; E : in Dictionary_Code) return Smaz_Tools.Score_Value is (Smaz_Tools.Score_Gain (Counts (E), Dict_Entry_Length (Dict, E))); -- Score value using the number of bytes saved using E function Score (Dict : in Dictionary; Counts : in Dictionary_Counts; E : in Dictionary_Code; Method : in Smaz_Tools.Methods.Enum) return Smaz_Tools.Score_Value is (Smaz_Tools.Score (Counts (E), Dict_Entry_Length (Dict, E), Method)); -- Scare value with dynamically chosen method end Natools.Smaz_Generic.Tools;
------------------------------------------------------------------------------ -- Copyright (c) 2016-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Smaz_Generic.Tools provides tools specific to the dictionary -- -- implementation. These tools are useful for dictionary manipulation, -- -- even though the intended use of this Smaz implementation is through a -- -- global constant dictionary object. -- ------------------------------------------------------------------------------ with Natools.Smaz_Tools; generic package Natools.Smaz_Generic.Tools is pragma Preelaborate; package String_Lists renames Smaz_Tools.String_Lists; function To_Dictionary (List : in String_Lists.List; Variable_Length_Verbatim : in Boolean) return Dictionary with Pre => String_Lists.Length (List) in 1 .. Dictionary_Code'Pos (Dictionary_Code'Last); -- Build a Dictionary object from a string list -- Note that Hash is set to a placeholder which unconditionnally -- raises Program_Error when called. function To_String_List (Dict : in Dictionary) return String_Lists.List; -- Convert a dictionary back to the corresponding list of words generic with procedure Put_Line (Line : String); procedure Print_Dictionary_In_Ada (Dict : in Dictionary; Hash_Image : in String := "TODO"; Max_Width : in Positive := 70; First_Prefix : in String := " := ("; Prefix : in String := " "; Half_Indent : in String := " "); -- Output Ada code corresponding to the value of the dictionary. -- Note that Prefix is the actual base indentation, while Half_Indent -- is added beyond Prefix before values continued on another line. -- Frist_Prefix is used instead of Prefix on the first line. -- All the defaults value are what was used to generate the constant -- in Natools.Smaz_Original. function Remove_Element (Dict : in Dictionary; Index : in Dictionary_Code) return Dictionary with Pre => Index <= Dict.Last_Code, Post => Dict.Last_Code = Dictionary_Code'Succ (Remove_Element'Result.Last_Code) and then (Index = Dictionary_Code'First or else (for all I in Dictionary_Code'First .. Dictionary_Code'Pred (Index) => Dict_Entry (Dict, I) = Dict_Entry (Remove_Element'Result, I))) and then (Index = Dict.Last_Code or else (for all I in Index .. Dictionary_Code'Pred (Dict.Last_Code) => Dict_Entry (Dict, Dictionary_Code'Succ (I)) = Dict_Entry (Remove_Element'Result, I))); -- Return a new dictionary equal to Dict without element for Index function Append_String (Dict : in Dictionary; Value : in String) return Dictionary with Pre => Dict.Last_Code < Dictionary_Code'Last and then Value'Length > 0, Post => Dict.Last_Code = Dictionary_Code'Pred (Append_String'Result.Last_Code) and then (for all I in Dictionary_Code'First .. Dict.Last_Code => Dict_Entry (Dict, I) = Dict_Entry (Append_String'Result, I)) and then Dict_Entry (Append_String'Result, Append_String'Result.Last_Code) = Value; -- Return a new dictionary with Value appended type Dictionary_Counts is array (Dictionary_Code) of Smaz_Tools.String_Count; procedure Evaluate_Dictionary (Dict : in Dictionary; Corpus : in String_Lists.List; Compressed_Size : out Ada.Streams.Stream_Element_Count; Counts : out Dictionary_Counts); procedure Evaluate_Dictionary_Partial (Dict : in Dictionary; Corpus_Entry : in String; Compressed_Size : in out Ada.Streams.Stream_Element_Count; Counts : in out Dictionary_Counts); -- Compress all strings of Corpus, returning the total number of -- compressed bytes and the number of uses for each dictionary -- element. function Worst_Index (Dict : in Dictionary; Counts : in Dictionary_Counts; Method : in Smaz_Tools.Methods.Enum) return Dictionary_Code; -- Return the element with worst score function Score_Encoded (Dict : in Dictionary; Counts : in Dictionary_Counts; E : in Dictionary_Code) return Smaz_Tools.Score_Value is (Smaz_Tools.Score_Encoded (Counts (E), Dict_Entry_Length (Dict, E))); -- Score value using the amount of encoded data using E function Score_Frequency (Dict : in Dictionary; Counts : in Dictionary_Counts; E : in Dictionary_Code) return Smaz_Tools.Score_Value is (Smaz_Tools.Score_Frequency (Counts (E), Dict_Entry_Length (Dict, E))); -- Score value using the number of times E was used function Score_Gain (Dict : in Dictionary; Counts : in Dictionary_Counts; E : in Dictionary_Code) return Smaz_Tools.Score_Value is (Smaz_Tools.Score_Gain (Counts (E), Dict_Entry_Length (Dict, E))); -- Score value using the number of bytes saved using E function Score (Dict : in Dictionary; Counts : in Dictionary_Counts; E : in Dictionary_Code; Method : in Smaz_Tools.Methods.Enum) return Smaz_Tools.Score_Value is (Smaz_Tools.Score (Counts (E), Dict_Entry_Length (Dict, E), Method)); -- Scare value with dynamically chosen method end Natools.Smaz_Generic.Tools;
fix the precondition of To_Dictionary
smaz_generic-tools: fix the precondition of To_Dictionary
Ada
isc
faelys/natools
5211b92324e5ff10bf1914fc5d6c636287af6c7a
src/os-linux/util-systems-dlls.ads
src/os-linux/util-systems-dlls.ads
----------------------------------------------------------------------- -- util-systems-dlls -- Unix shared library support -- 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 System; with Interfaces.C; with Util.Systems.Constants; package Util.Systems.DLLs is -- The shared library handle. type Handle is private; Null_Handle : constant Handle; -- Exception raised when there is a problem loading a shared library. Load_Error : exception; -- Exception raised when a symbol cannot be found in a shared library. Not_Found : exception; subtype Flags is Interfaces.C.int; -- Load the shared library with the given name or path and return a library handle. -- Raises the <tt>Load_Error</tt> exception if the library cannot be loaded. function Load (Path : in String; Mode : in Flags := Util.Systems.Constants.RTLD_LAZY) return Handle; -- Unload the shared library. procedure Unload (Lib : in Handle); -- Get a global symbol with the given name in the library. -- Raises the <tt>Not_Found</tt> exception if the symbol does not exist. function Get_Symbol (Lib : in Handle; Name : in String) return System.Address; private type Handle is new System.Address; Null_Handle : constant Handle := Handle (System.Null_Address); end Util.Systems.DLLs;
----------------------------------------------------------------------- -- util-systems-dlls -- Unix shared library support -- 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 System; with Interfaces.C; with Util.Systems.Constants; package Util.Systems.DLLs is -- The shared library handle. type Handle is private; Null_Handle : constant Handle; -- Exception raised when there is a problem loading a shared library. Load_Error : exception; -- Exception raised when a symbol cannot be found in a shared library. Not_Found : exception; subtype Flags is Interfaces.C.int; Extension : constant String := ".so"; -- Load the shared library with the given name or path and return a library handle. -- Raises the <tt>Load_Error</tt> exception if the library cannot be loaded. function Load (Path : in String; Mode : in Flags := Util.Systems.Constants.RTLD_LAZY) return Handle; -- Unload the shared library. procedure Unload (Lib : in Handle); -- Get a global symbol with the given name in the library. -- Raises the <tt>Not_Found</tt> exception if the symbol does not exist. function Get_Symbol (Lib : in Handle; Name : in String) return System.Address; private type Handle is new System.Address; Null_Handle : constant Handle := Handle (System.Null_Address); end Util.Systems.DLLs;
Define the extension for shared libraries
Define the extension for shared libraries
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
23c4b9406a90b45ec9cfbbf08979bb4fe14d8227
src/gen-commands-model.adb
src/gen-commands-model.adb
----------------------------------------------------------------------- -- gen-commands-model -- Model creation command for dynamo -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Gen.Artifacts; with GNAT.Command_Line; with Gen.Utils; with Util.Files; package body Gen.Commands.Model is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name); use GNAT.Command_Line; use Ada.Command_Line; Arg1 : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else ""); Arg2 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else ""); Root_Dir : constant String := Generator.Get_Result_Directory; Dir : constant String := Util.Files.Compose (Root_Dir, "db"); begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Gen.Commands.Usage; return; end if; Generator.Read_Project ("dynamo.xml"); Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); if Args.Get_Count = 1 then -- Verify that we can use the name for an Ada identifier. if not Gen.Utils.Is_Valid_Name (Arg1) then Generator.Error ("The mapping name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid mapping name: " & Arg1; end if; Generator.Set_Global ("moduleName", ""); Generator.Set_Global ("modelName", Arg1); else -- Verify that we can use the name for an Ada identifier. if not Gen.Utils.Is_Valid_Name (Arg1) then Generator.Error ("The module name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid module name: " & Arg1; end if; -- Likewise for the mapping name. if not Gen.Utils.Is_Valid_Name (Arg2) then Generator.Error ("The mapping name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid mapping name: " & Arg2; end if; Generator.Set_Global ("moduleName", Arg1); Generator.Set_Global ("modelName", Arg2); end if; Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "add-model"); -- If the generation succeeds, run the generate command to generate the Ada files. if Generator.Get_Status = Ada.Command_Line.Success then Generator.Set_Result_Directory (Root_Dir); Generator.Set_Force_Save (True); Gen.Generator.Read_Models (Generator, "db"); -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("add-model: Add a new database table model to the application"); Put_Line ("Usage: add-model [MODULE] NAME"); New_Line; Put_Line (" The database table model is an XML file that describes the mapping"); Put_Line (" for of a database table to an Ada representation."); Put_Line (" The XML description is similar to Hibernate mapping files."); Put_Line (" (See http://docs.jboss.org/hibernate/core/3.6/" & "reference/en-US/html/mapping.html)"); Put_Line (" If a MODULE is specified, the Ada package will be: " & "<PROJECT>.<MODULE>.Model.<NAME>"); Put_Line (" Otherwise, the Ada package will be: <PROJECT>.Model.<NAME>"); end Help; end Gen.Commands.Model;
----------------------------------------------------------------------- -- gen-commands-model -- Model creation command for dynamo -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Gen.Artifacts; with Gen.Utils; with Util.Files; package body Gen.Commands.Model is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name); use Ada.Command_Line; Arg1 : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else ""); Arg2 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else ""); Root_Dir : constant String := Generator.Get_Result_Directory; Dir : constant String := Util.Files.Compose (Root_Dir, "db"); begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Gen.Commands.Usage; return; end if; Generator.Read_Project ("dynamo.xml"); Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); if Args.Get_Count = 1 then -- Verify that we can use the name for an Ada identifier. if not Gen.Utils.Is_Valid_Name (Arg1) then Generator.Error ("The mapping name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid mapping name: " & Arg1; end if; Generator.Set_Global ("moduleName", ""); Generator.Set_Global ("modelName", Arg1); else -- Verify that we can use the name for an Ada identifier. if not Gen.Utils.Is_Valid_Name (Arg1) then Generator.Error ("The module name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid module name: " & Arg1; end if; -- Likewise for the mapping name. if not Gen.Utils.Is_Valid_Name (Arg2) then Generator.Error ("The mapping name should be a valid Ada identifier."); raise Gen.Generator.Fatal_Error with "Invalid mapping name: " & Arg2; end if; Generator.Set_Global ("moduleName", Arg1); Generator.Set_Global ("modelName", Arg2); end if; Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "add-model"); -- If the generation succeeds, run the generate command to generate the Ada files. if Generator.Get_Status = Ada.Command_Line.Success then Generator.Set_Result_Directory (Root_Dir); Generator.Set_Force_Save (True); Gen.Generator.Read_Models (Generator, "db"); -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("add-model: Add a new database table model to the application"); Put_Line ("Usage: add-model [MODULE] NAME"); New_Line; Put_Line (" The database table model is an XML file that describes the mapping"); Put_Line (" for of a database table to an Ada representation."); Put_Line (" The XML description is similar to Hibernate mapping files."); Put_Line (" (See http://docs.jboss.org/hibernate/core/3.6/" & "reference/en-US/html/mapping.html)"); Put_Line (" If a MODULE is specified, the Ada package will be: " & "<PROJECT>.<MODULE>.Model.<NAME>"); Put_Line (" Otherwise, the Ada package will be: <PROJECT>.Model.<NAME>"); end Help; end Gen.Commands.Model;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
e24aa3604c807fc4df672af2ad45557f04a145cc
src/util-log-appenders.ads
src/util-log-appenders.ads
----------------------------------------------------------------------- -- Appenders -- Log appenders -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 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.Text_IO; with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Util.Properties; limited with Util.Log.Loggers; -- The log <b>Appender</b> will handle the low level operations to write -- the log content to a file, the console, a database. package Util.Log.Appenders is use Ada.Strings.Unbounded; -- ------------------------------ -- Log event -- ------------------------------ -- The <b>Log_Event</b> represent a log message reported by one of the -- <b>log</b> operation (Debug, Info, Warn, Error). type Log_Event is record -- The log message (formatted) Message : Unbounded_String; -- The timestamp when the message was produced. Time : Ada.Calendar.Time; -- The log level Level : Level_Type; -- The logger Logger : access Util.Log.Loggers.Logger_Info; end record; -- The layout type to indicate how to format the message. -- Unlike Logj4, there is no customizable layout. type Layout_Type is ( -- The <b>message</b> layout with only the log message. -- Ex: "Cannot open file" MESSAGE, -- The <b>level-message</b> layout with level and message. -- Ex: "ERROR: Cannot open file" LEVEL_MESSAGE, -- The <b>date-level-message</b> layout with date -- Ex: "2011-03-04 12:13:34 ERROR: Cannot open file" DATE_LEVEL_MESSAGE, -- The <b>full</b> layout with everything (the default). -- Ex: "2011-03-04 12:13:34 ERROR - my.application - Cannot open file" FULL); -- ------------------------------ -- Log appender -- ------------------------------ type Appender is abstract new Ada.Finalization.Limited_Controlled with private; type Appender_Access is access all Appender'Class; -- Get the log level that triggers display of the log events function Get_Level (Self : in Appender) return Level_Type; -- Set the log level. procedure Set_Level (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Level : in Level_Type); -- Set the log layout format. procedure Set_Layout (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Layout : in Layout_Type); -- Format the event into a string function Format (Self : in Appender; Event : in Log_Event) return String; -- Append a log event to the appender. Depending on the log level -- defined on the appender, the event can be taken into account or -- ignored. procedure Append (Self : in out Appender; Event : in Log_Event) is abstract; -- Flush the log events. procedure Flush (Self : in out Appender) is abstract; -- ------------------------------ -- File appender -- ------------------------------ -- Write log events to a file type File_Appender is new Appender with private; type File_Appender_Access is access all File_Appender'Class; overriding procedure Append (Self : in out File_Appender; Event : in Log_Event); -- Set the file where the appender will write the logs. -- When <tt>Append</tt> is true, the log message are appended to the existing file. -- When set to false, the file is cleared before writing new messages. procedure Set_File (Self : in out File_Appender; Path : in String; Append : in Boolean := True); -- 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_File_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; -- ------------------------------ -- Console appender -- ------------------------------ -- Write log events to the console type Console_Appender is new Appender with private; type Console_Appender_Access is access all Console_Appender'Class; overriding procedure Append (Self : in out Console_Appender; Event : in Log_Event); -- Flush the log events. overriding procedure Flush (Self : in out Console_Appender); -- Create a console appender and configure it according to the properties function Create_Console_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; -- ------------------------------ -- List appender -- ------------------------------ -- Write log events to a list of appenders type List_Appender is new Appender with private; type List_Appender_Access is access all List_Appender'Class; -- Max number of appenders that can be added to the list. -- In most cases, 2 or 3 appenders will be used. MAX_APPENDERS : constant Natural := 10; overriding procedure Append (Self : in out List_Appender; Event : in Log_Event); -- Flush the log events. overriding procedure Flush (Self : in out List_Appender); -- Add the appender to the list. procedure Add_Appender (Self : in out List_Appender; Object : in Appender_Access); -- Create a list appender and configure it according to the properties function Create_List_Appender return List_Appender_Access; private type Appender is abstract new Ada.Finalization.Limited_Controlled with record Level : Level_Type := INFO_LEVEL; Layout : Layout_Type := FULL; end record; type File_Appender is new Appender with record Output : Ada.Text_IO.File_Type; Immediate_Flush : Boolean := False; end record; type Appender_Array_Access is array (1 .. MAX_APPENDERS) of Appender_Access; type List_Appender is new Appender with record Appenders : Appender_Array_Access; Count : Natural := 0; end record; type Console_Appender is new Appender with null record; end Util.Log.Appenders;
----------------------------------------------------------------------- -- util-log-appenders -- Log appenders -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Util.Properties; limited with Util.Log.Loggers; -- The log <b>Appender</b> will handle the low level operations to write -- the log content to a file, the console, a database. package Util.Log.Appenders is use Ada.Strings.Unbounded; -- ------------------------------ -- Log event -- ------------------------------ -- The <b>Log_Event</b> represent a log message reported by one of the -- <b>log</b> operation (Debug, Info, Warn, Error). type Log_Event is record -- The log message (formatted) Message : Unbounded_String; -- The timestamp when the message was produced. Time : Ada.Calendar.Time; -- The log level Level : Level_Type; -- The logger Logger : access Util.Log.Loggers.Logger_Info; end record; -- The layout type to indicate how to format the message. -- Unlike Logj4, there is no customizable layout. type Layout_Type is ( -- The <b>message</b> layout with only the log message. -- Ex: "Cannot open file" MESSAGE, -- The <b>level-message</b> layout with level and message. -- Ex: "ERROR: Cannot open file" LEVEL_MESSAGE, -- The <b>date-level-message</b> layout with date -- Ex: "2011-03-04 12:13:34 ERROR: Cannot open file" DATE_LEVEL_MESSAGE, -- The <b>full</b> layout with everything (the default). -- Ex: "2011-03-04 12:13:34 ERROR - my.application - Cannot open file" FULL); -- ------------------------------ -- Log appender -- ------------------------------ type Appender is abstract new Ada.Finalization.Limited_Controlled with private; type Appender_Access is access all Appender'Class; -- Get the log level that triggers display of the log events function Get_Level (Self : in Appender) return Level_Type; -- Set the log level. procedure Set_Level (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Level : in Level_Type); -- Set the log layout format. procedure Set_Layout (Self : in out Appender; Name : in String; Properties : in Util.Properties.Manager; Layout : in Layout_Type); -- Format the event into a string function Format (Self : in Appender; Event : in Log_Event) return String; -- Append a log event to the appender. Depending on the log level -- defined on the appender, the event can be taken into account or -- ignored. procedure Append (Self : in out Appender; Event : in Log_Event) is abstract; -- Flush the log events. procedure Flush (Self : in out Appender) is abstract; -- ------------------------------ -- File appender -- ------------------------------ -- Write log events to a file type File_Appender is new Appender with private; type File_Appender_Access is access all File_Appender'Class; overriding procedure Append (Self : in out File_Appender; Event : in Log_Event); -- Set the file where the appender will write the logs. -- When <tt>Append</tt> is true, the log message are appended to the existing file. -- When set to false, the file is cleared before writing new messages. procedure Set_File (Self : in out File_Appender; Path : in String; Append : in Boolean := True); -- 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_File_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; -- ------------------------------ -- Console appender -- ------------------------------ -- Write log events to the console type Console_Appender is new Appender with private; type Console_Appender_Access is access all Console_Appender'Class; overriding procedure Append (Self : in out Console_Appender; Event : in Log_Event); -- Flush the log events. overriding procedure Flush (Self : in out Console_Appender); -- Create a console appender and configure it according to the properties function Create_Console_Appender (Name : in String; Properties : in Util.Properties.Manager; Default : in Level_Type) return Appender_Access; -- ------------------------------ -- List appender -- ------------------------------ -- Write log events to a list of appenders type List_Appender is new Appender with private; type List_Appender_Access is access all List_Appender'Class; -- Max number of appenders that can be added to the list. -- In most cases, 2 or 3 appenders will be used. MAX_APPENDERS : constant Natural := 10; overriding procedure Append (Self : in out List_Appender; Event : in Log_Event); -- Flush the log events. overriding procedure Flush (Self : in out List_Appender); -- Add the appender to the list. procedure Add_Appender (Self : in out List_Appender; Object : in Appender_Access); -- Create a list appender and configure it according to the properties function Create_List_Appender return List_Appender_Access; private type Appender is abstract new Ada.Finalization.Limited_Controlled with record Level : Level_Type := INFO_LEVEL; Layout : Layout_Type := FULL; end record; type File_Appender is new Appender with record Output : Ada.Text_IO.File_Type; Immediate_Flush : Boolean := False; end record; type Appender_Array_Access is array (1 .. MAX_APPENDERS) of Appender_Access; type List_Appender is new Appender with record Appenders : Appender_Array_Access; Count : Natural := 0; end record; type Console_Appender is new Appender with null record; end Util.Log.Appenders;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b37f3c1bbc950a342adad4665f8eac89f4664e97
src/gen-generator.ads
src/gen-generator.ads
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with ASF.Servlets; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; with Gen.Artifacts.Yaml; package Gen.Generator is -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in Ada.Strings.Unbounded.Unbounded_String; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in String); -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : Unbounded_String; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Object_Access is access all Util.Beans.Objects.Object; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Output base directory. Output_Dir : Ada.Strings.Unbounded.Unbounded_String; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : Object_Access; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : Object_Access; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : Object_Access; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- Yaml model files support. Yaml : Gen.Artifacts.Yaml.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; -- A fake servlet for template evaluation. Servlet : ASF.Servlets.Servlet_Access; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Hashed_Maps; with Util.Beans.Objects; with Util.Properties; with ASF.Applications.Main; with ASF.Contexts.Faces; with ASF.Servlets; with Gen.Model.Packages; with Gen.Model.Projects; with Gen.Artifacts.Hibernate; with Gen.Artifacts.Query; with Gen.Artifacts.Mappings; with Gen.Artifacts.Distribs; with Gen.Artifacts.XMI; with Gen.Artifacts.Yaml; package Gen.Generator is -- A fatal error that prevents the generator to proceed has occurred. Fatal_Error : exception; G_URI : constant String := "http://code.google.com/p/ada-ado/generator"; type Package_Type is (PACKAGE_MODEL, PACKAGE_FORMS); type Mapping_File is record Path : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Text_IO.File_Type; end record; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with private; -- Initialize the generator procedure Initialize (H : in out Handler; Config_Dir : in Ada.Strings.Unbounded.Unbounded_String; Debug : in Boolean); -- Get the configuration properties. function Get_Properties (H : in Handler) return Util.Properties.Manager; -- Report an error and set the exit status accordingly procedure Error (H : in out Handler; Message : in String; Arg1 : in String; Arg2 : in String := ""); overriding procedure Error (H : in out Handler; Message : in String); -- Report an info message. procedure Info (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); -- Read the XML package file procedure Read_Package (H : in out Handler; File : in String); -- Read the model mapping types and initialize the hibernate artifact. procedure Read_Mappings (H : in out Handler); -- Read the XML model file procedure Read_Model (H : in out Handler; File : in String; Silent : in Boolean); -- Read the model and query files stored in the application directory <b>db</b>. procedure Read_Models (H : in out Handler; Dirname : in String); -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (H : in out Handler; File : in String; Recursive : in Boolean := False); -- Prepare the model by checking, verifying and initializing it after it is completely known. procedure Prepare (H : in out Handler); -- Finish the generation. Some artifacts could generate other files that take into -- account files generated previously. procedure Finish (H : in out Handler); -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (H : in out Handler; Name : in String; Mode : in Gen.Artifacts.Iteration_Mode; Mapping : in String); -- Enable the generation of the Ada package given by the name. By default all the Ada -- packages found in the model are generated. When called, this enables the generation -- only for the Ada packages registered here. procedure Enable_Package_Generation (H : in out Handler; Name : in String); -- Save the content generated by the template generator. procedure Save_Content (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); -- Generate the code using the template file procedure Generate (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; File : in String; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate the code using the template file procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access; Save : not null access procedure (H : in out Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String)); -- Generate all the code for the templates activated through <b>Add_Generation</b>. procedure Generate_All (H : in out Handler); -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Gen.Artifacts.Iteration_Mode; Name : in String); -- Set the directory where template files are stored. procedure Set_Template_Directory (H : in out Handler; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Set the directory where results files are generated. procedure Set_Result_Directory (H : in out Handler; Path : in String); -- Get the result directory path. function Get_Result_Directory (H : in Handler) return String; -- Get the project plugin directory path. function Get_Plugin_Directory (H : in Handler) return String; -- Get the config directory path. function Get_Config_Directory (H : in Handler) return String; -- Get the dynamo installation directory path. function Get_Install_Directory (H : in Handler) return String; -- Return the search directories that the AWA application can use to find files. -- The search directories is built by using the project dependencies. function Get_Search_Directories (H : in Handler) return String; -- Get the exit status -- Returns 0 if the generation was successful -- Returns 1 if there was a generation error function Get_Status (H : in Handler) return Ada.Command_Line.Exit_Status; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in String := "") return String; -- Get the configuration parameter. function Get_Parameter (H : in Handler; Name : in String; Default : in Boolean := False) return Boolean; -- Set the force-save file mode. When False, if the generated file exists already, -- an error message is reported. procedure Set_Force_Save (H : in out Handler; To : in Boolean); -- Set the project name. procedure Set_Project_Name (H : in out Handler; Name : in String); -- Get the project name. function Get_Project_Name (H : in Handler) return String; -- Set the project property. procedure Set_Project_Property (H : in out Handler; Name : in String; Value : in String); -- Get the project property identified by the given name. If the project property -- does not exist, returns the default value. Project properties are loaded -- by <b>Read_Project</b>. function Get_Project_Property (H : in Handler; Name : in String; Default : in String := "") return String; -- Save the project description and parameters. procedure Save_Project (H : in out Handler); -- Get the path of the last generated file. function Get_Generated_File (H : in Handler) return String; -- Update the project model through the <b>Process</b> procedure. procedure Update_Project (H : in out Handler; Process : not null access procedure (P : in out Model.Projects.Root_Project_Definition)); -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (H : in Handler; Process : not null access procedure (Dir : in String)); private use Ada.Strings.Unbounded; use Gen.Artifacts; type Template_Context is record Mode : Gen.Artifacts.Iteration_Mode; Mapping : Unbounded_String; end record; package Template_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Template_Context, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Object_Access is access all Util.Beans.Objects.Object; type Handler is new ASF.Applications.Main.Application and Gen.Artifacts.Generator with record Conf : ASF.Applications.Config; -- Config directory. Config_Dir : Ada.Strings.Unbounded.Unbounded_String; -- Output base directory. Output_Dir : Ada.Strings.Unbounded.Unbounded_String; Model : aliased Gen.Model.Packages.Model_Definition; Status : Ada.Command_Line.Exit_Status := 0; -- The file that must be saved (the file attribute in <f:view>. File : Object_Access; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : Object_Access; -- Indicates whether the file must be ignored after the generation. -- This is the ignore attribute in <f:view>. It is intended to be used for the package -- body generation to skip that in some cases when it turns out there is no operation. Ignore : Object_Access; -- Whether the AdaMappings.xml file was loaded or not. Type_Mapping_Loaded : Boolean := False; -- The root project document. Project : aliased Gen.Model.Projects.Root_Project_Definition; -- Hibernate XML artifact Hibernate : Gen.Artifacts.Hibernate.Artifact; -- Query generation artifact. Query : Gen.Artifacts.Query.Artifact; -- Type mapping artifact. Mappings : Gen.Artifacts.Mappings.Artifact; -- The distribution artifact. Distrib : Gen.Artifacts.Distribs.Artifact; -- Ada generation from UML-XMI models. XMI : Gen.Artifacts.XMI.Artifact; -- Yaml model files support. Yaml : Gen.Artifacts.Yaml.Artifact; -- The list of templates that must be generated. Templates : Template_Map.Map; -- Force the saving of a generated file, even if a file already exist. Force_Save : Boolean := True; -- A fake servlet for template evaluation. Servlet : ASF.Servlets.Servlet_Access; end record; -- Execute the lifecycle phases on the faces context. overriding procedure Execute_Lifecycle (App : in Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end Gen.Generator;
Implement the Error procedure from the Util.Log.Logging interface
Implement the Error procedure from the Util.Log.Logging interface
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2b804b90608c8a7932b4610dfa48821c5c5beef1
examples/src/orka_7_half.adb
examples/src/orka_7_half.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Text_IO; with GL.Types; with Orka.Types; procedure Orka_7_Half is use type GL.Types.Single; Numbers : constant GL.Types.Single_Array := (0.0, 0.5, -0.5, 1.0, -1.0, 0.1, -0.1, 0.0, 0.1234, -0.123456, 10.1234, 20.1234, 50.1234, 100.1234, 1000.1234); Half_Numbers : constant GL.Types.Half_Array := Orka.Types.Convert (Numbers); Single_Numbers : constant GL.Types.Single_Array := Orka.Types.Convert (Half_Numbers); begin for Number of Numbers loop Ada.Text_IO.Put_Line (GL.Types.Single'Image (Number)); end loop; Ada.Text_IO.Put_Line ("------------"); for Number of Single_Numbers loop Ada.Text_IO.Put_Line (GL.Types.Single'Image (Number)); end loop; end Orka_7_Half;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2016 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Text_IO; with GL.Types; with Orka.Types; procedure Orka_7_Half is use type GL.Types.Single; Numbers : constant GL.Types.Single_Array := (0.0, 0.5, -0.5, 1.0, -1.0, 0.1, -0.1, 0.0, 0.1234, -0.123456, 10.1234, 20.1234, 50.1234, 100.1234, 1000.1234); Half_Numbers : GL.Types.Half_Array (Numbers'Range); Single_Numbers : GL.Types.Single_Array (Half_Numbers'Range); begin Orka.Types.Convert (Numbers, Half_Numbers); Orka.Types.Convert (Half_Numbers, Single_Numbers); for Number of Numbers loop Ada.Text_IO.Put_Line (GL.Types.Single'Image (Number)); end loop; Ada.Text_IO.Put_Line ("------------"); for Number of Single_Numbers loop Ada.Text_IO.Put_Line (GL.Types.Single'Image (Number)); end loop; end Orka_7_Half;
Fix compilation after changing function Convert to a procedure
examples: Fix compilation after changing function Convert to a procedure Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
38b44a65a9c094284553248c6ea4b5bb40a0d89b
matp/src/events/mat-events-tools.ads
matp/src/events/mat-events-tools.ads
----------------------------------------------------------------------- -- mat-events-tools - Profiler Events Description -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; package MAT.Events.Tools is Not_Found : exception; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event_Type); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Target_Event_Type; type Event_Info_Type is record First_Event : Target_Event_Type; Last_Event : Target_Event_Type; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; -- The frame key is composed of the frame address and the frame level. type Frame_Key_Type is record Addr : MAT.Types.Target_Addr; Level : Natural; end record; function "<" (Left, Right : in Frame_Key_Type) return Boolean; -- Ordered map to collect event info statistics by <frame, level> pair. package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Frame_Key_Type, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); type Frame_Info_Type is record Key : Frame_Key_Type; Info : Event_Info_Type; end record; package Frame_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Frame_Info_Type); subtype Frame_Info_Vector is Frame_Info_Vectors.Vector; subtype Frame_Info_Cursor is Frame_Info_Vectors.Cursor; -- Extract from the frame info map, the list of frame event info sorted -- on the frame level and slot size. procedure Build_Frame_Info (Map : in Frame_Event_Info_Map; List : in out Frame_Info_Vector); end MAT.Events.Tools;
----------------------------------------------------------------------- -- mat-events-tools - Profiler Events Description -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; package MAT.Events.Tools is Not_Found : exception; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event_Type); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; -- Find in the list the first event with the given type. -- Raise <tt>Not_Found</tt> if the list does not contain such event. function Find (List : in Target_Event_Vector; Kind : in Probe_Index_Type) return Target_Event_Type; type Event_Info_Type is record First_Event : Target_Event_Type; Last_Event : Target_Event_Type; Frame_Addr : MAT.Types.Target_Addr; Count : Natural; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; Alloc_Size : MAT.Types.Target_Size := 0; Free_Size : MAT.Types.Target_Size := 0; end record; -- Collect statistics information about events. procedure Collect_Info (Into : in out Event_Info_Type; Event : in MAT.Events.Target_Event_Type); package Size_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Event_Info_Type); subtype Size_Event_Info_Map is Size_Event_Info_Maps.Map; subtype Size_Event_Info_Cursor is Size_Event_Info_Maps.Cursor; -- The frame key is composed of the frame address and the frame level. type Frame_Key_Type is record Addr : MAT.Types.Target_Addr; Level : Natural; end record; function "<" (Left, Right : in Frame_Key_Type) return Boolean; -- Ordered map to collect event info statistics by <frame, level> pair. package Frame_Event_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Frame_Key_Type, Element_Type => Event_Info_Type); subtype Frame_Event_Info_Map is Frame_Event_Info_Maps.Map; subtype Frame_Event_Info_Cursor is Frame_Event_Info_Maps.Cursor; package Event_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Event_Info_Type); subtype Event_Info_Vector is Event_Info_Vectors.Vector; subtype Event_Info_Cursor is Event_Info_Vectors.Cursor; -- Extract from the frame info map, the list of event info sorted on the count. procedure Build_Event_Info (Map : in Frame_Event_Info_Map; List : in out Event_Info_Vector); type Frame_Info_Type is record Key : Frame_Key_Type; Info : Event_Info_Type; end record; package Frame_Info_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Frame_Info_Type); subtype Frame_Info_Vector is Frame_Info_Vectors.Vector; subtype Frame_Info_Cursor is Frame_Info_Vectors.Cursor; -- Extract from the frame info map, the list of frame event info sorted -- on the frame level and slot size. procedure Build_Frame_Info (Map : in Frame_Event_Info_Map; List : in out Frame_Info_Vector); end MAT.Events.Tools;
Declare the Collect_Info procedure
Declare the Collect_Info procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
5a6ccbd3699f34064d0f33911ca82a8041b10366
mat/src/mat-readers-streams-sockets.adb
mat/src/mat-readers-streams-sockets.adb
----------------------------------------------------------------------- -- 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.Streams; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; -- Address.Addr := GNAT.Sockets.Addresses (Get_Host_By_Name (S.Get_Host), 1); -- Address.Addr := GNAT.Sockets.Any_Inet_Addr; -- Address.Port := 4096; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); -- Address := GNAT.Sockets.Get_Socket_Name (Server); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Socket_Reader_Task; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Reading server stream"); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader'Unchecked_Access, Address); end Open; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; 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.Streams; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.Listener.Start (Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (S : in Socket_Reader_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := S; -- Address.Addr := GNAT.Sockets.Addresses (Get_Host_By_Name (S.Get_Host), 1); -- Address.Addr := GNAT.Sockets.Any_Inet_Addr; -- Address.Port := 4096; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); -- Address := GNAT.Sockets.Get_Socket_Name (Server); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; while not Instance.Stop loop GNAT.Sockets.Accept_Socket (Server, Socket, Peer, 1.0, null, Status); if Socket /= GNAT.Sockets.No_Socket then Instance.Socket.Open (Socket); Instance.Read_All; end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Socket_Reader_Task; -- Open the socket to accept connections. procedure Open (Reader : in out Socket_Reader_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Reading server stream"); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.Socket'Unchecked_Access, Output => null); Reader.Server.Start (Reader'Unchecked_Access, Address); end Open; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
Implement the Start operation
Implement the Start operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
07da71b841dbbc7373e1998b4ae96cd3a851967e
mat/src/mat-readers-streams-sockets.adb
mat/src/mat-readers-streams-sockets.adb
----------------------------------------------------------------------- -- 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.Streams; with Util.Log.Loggers; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is use type GNAT.Sockets.Selector_Type; begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- 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) is Reader : Socket_Reader_Type_Access := new Socket_Reader_Type; begin Reader.Server.Start (Reader, Client); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then GNAT.Sockets.Close_Socket (Client); end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; Status : GNAT.Sockets.Selector_Status; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; 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.Streams; with Util.Log.Loggers; package body MAT.Readers.Streams.Sockets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Sockets"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Initialize the socket listener. -- ------------------------------ overriding procedure Initialize (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Create_Selector (Listener.Accept_Selector); end Initialize; -- ------------------------------ -- Destroy the socket listener. -- ------------------------------ overriding procedure Finalize (Listener : in out Socket_Listener_Type) is use type GNAT.Sockets.Selector_Type; begin GNAT.Sockets.Close_Selector (Listener.Accept_Selector); end Finalize; -- ------------------------------ -- Open the socket to accept connections and start the listener task. -- ------------------------------ procedure Start (Listener : in out Socket_Listener_Type; Address : in GNAT.Sockets.Sock_Addr_Type) is begin Log.Info ("Starting the listener socket task"); Listener.Listener.Start (Listener'Unchecked_Access, Address); end Start; -- ------------------------------ -- Stop the listener socket. -- ------------------------------ procedure Stop (Listener : in out Socket_Listener_Type) is begin GNAT.Sockets.Abort_Selector (Listener.Accept_Selector); end Stop; -- ------------------------------ -- 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) is Reader : constant Socket_Reader_Type_Access := new Socket_Reader_Type; begin Reader.Server.Start (Reader, Client); end Create_Target; task body Socket_Listener_Task is use type GNAT.Sockets.Socket_Type; use type GNAT.Sockets.Selector_Status; Peer : GNAT.Sockets.Sock_Addr_Type; Server : GNAT.Sockets.Socket_Type; Instance : Socket_Listener_Type_Access; Client : GNAT.Sockets.Socket_Type; Selector_Status : GNAT.Sockets.Selector_Status; begin select accept Start (Listener : in Socket_Listener_Type_Access; Address : in GNAT.Sockets.Sock_Addr_Type) do Instance := Listener; GNAT.Sockets.Create_Socket (Server); GNAT.Sockets.Set_Socket_Option (Server, GNAT.Sockets.Socket_Level, (GNAT.Sockets.Reuse_Address, True)); GNAT.Sockets.Bind_Socket (Server, Address); GNAT.Sockets.Listen_Socket (Server); end Start; or terminate; end select; loop GNAT.Sockets.Accept_Socket (Server => Server, Socket => Client, Address => Peer, Timeout => GNAT.Sockets.Forever, Selector => Instance.Accept_Selector'Access, Status => Selector_Status); exit when Selector_Status = GNAT.Sockets.Aborted; if Selector_Status = GNAT.Sockets.Completed then Instance.Create_Target (Client => Client, Address => Peer); GNAT.Sockets.Close_Socket (Client); end if; end loop; GNAT.Sockets.Close_Socket (Server); end Socket_Listener_Task; task body Socket_Reader_Task is use type GNAT.Sockets.Socket_Type; Instance : Socket_Reader_Type_Access; Socket : GNAT.Sockets.Socket_Type; begin select accept Start (Reader : in Socket_Reader_Type_Access; Client : in GNAT.Sockets.Socket_Type) do Instance := Reader; Socket := Client; end Start; or terminate; end select; Instance.Socket.Open (Socket); Instance.Read_All; GNAT.Sockets.Close_Socket (Socket); exception when E : others => Log.Error ("Exception", E); GNAT.Sockets.Close_Socket (Socket); end Socket_Reader_Task; procedure Close (Reader : in out Socket_Reader_Type) is begin Reader.Stop := True; end Close; end MAT.Readers.Streams.Sockets;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8328c114f7e81547c7bff2f5d87c82c8ed70c3c2
awa/plugins/awa-images/src/awa-images-beans.adb
awa/plugins/awa-images/src/awa-images-beans.adb
----------------------------------------------------------------------- -- awa-images-beans -- Image Ada Beans -- 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 ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Services.Contexts; with AWA.Storages.Modules; package body AWA.Images.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Load the list of images associated with the current folder. -- ------------------------------ overriding procedure Load_Files (Storage : in Image_List_Bean) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Images.Models.Query_Image_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query); Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True; end Load_Files; overriding function Get_Value (List : in Image_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "images" then return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then -- if not List.Init_Flags (INIT_FOLDER) then -- Load_Folder (List); -- end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Image_List_Bean bean instance. -- ------------------------------ function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); Object : constant Image_List_Bean_Access := new Image_List_Bean; begin Object.Module := AWA.Storages.Modules.Get_Storage_Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Image_List_Bean := Object.Image_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Image_List_Bean; overriding procedure Load (Into : in out Image_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Images.Models.Query_Image_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Image_Bean bean instance. -- ------------------------------ function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Image_Bean_Access := new Image_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Image_Bean; end AWA.Images.Beans;
----------------------------------------------------------------------- -- awa-images-beans -- Image Ada Beans -- Copyright (C) 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Services.Contexts; with AWA.Storages.Modules; package body AWA.Images.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- Load the list of images associated with the current folder. -- ------------------------------ overriding procedure Load_Files (Storage : in out Image_List_Bean) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (AWA.Storages.Beans.INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Images.Models.Query_Image_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Images.Models.List (Storage.Image_List_Bean.all, Session, Query); Storage.Flags (AWA.Storages.Beans.INIT_FILE_LIST) := True; end Load_Files; overriding function Get_Value (List : in Image_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "images" then return Util.Beans.Objects.To_Object (Value => List.Image_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folders" then return Util.Beans.Objects.To_Object (Value => List.Folder_List_Bean, Storage => Util.Beans.Objects.STATIC); elsif Name = "folder" then -- if not List.Init_Flags (INIT_FOLDER) then -- Load_Folder (List); -- end if; if List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Create the Image_List_Bean bean instance. -- ------------------------------ function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); Object : constant Image_List_Bean_Access := new Image_List_Bean; begin Object.Module := AWA.Storages.Modules.Get_Storage_Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Image_List_Bean := Object.Image_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Image_List_Bean; overriding procedure Load (Into : in out Image_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Images.Models.Query_Image_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Image_Bean bean instance. -- ------------------------------ function Create_Image_Bean (Module : in AWA.Images.Modules.Image_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Image_Bean_Access := new Image_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Image_Bean; end AWA.Images.Beans;
Change Load_Files to accept in out parameter
Change Load_Files to accept in out parameter
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e02b67071a7e769525b06471c8ce49c574b17eda
awa/plugins/awa-questions/src/awa-questions.ads
awa/plugins/awa-questions/src/awa-questions.ads
----------------------------------------------------------------------- -- awa-questions -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package AWA.Questions is end AWA.Questions;
----------------------------------------------------------------------- -- awa-questions -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package AWA.Questions is pragma Preelaborate; end AWA.Questions;
Add Preelaborate
Add Preelaborate
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e9e3892057fbcee00683b727a427c61318522297
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with ADO.Sessions; with AWA.Events; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Definition; with Security.Permissions; -- == Events == -- The <tt>wikis</tt> exposes a number of events which are posted when some action -- are performed at the service level. -- -- === wiki-create-page === -- This event is posted when a new wiki page is created. -- -- === wiki-create-content === -- This event is posted when a new wiki page content is created. Each time a wiki page is -- modified, a new wiki page content is created and this event is posted. -- package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- Event posted when a new wiki page is created. package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page"); -- Event posted when a new wiki content is created. package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content"); -- Define the read wiki page counter. package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count"); package Wiki_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class); subtype Listener is Wiki_Lifecycle.Listener; -- The configuration parameter that defines a list of wiki page ID to copy when a new -- wiki space is created. PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list"; -- Exception raised when a wiki page name is already used for the wiki space. Name_Used : exception; -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the image prefix that was configured for the Wiki module. function Get_Image_Prefix (Module : in Wiki_Module) return Ada.Strings.Unbounded.Unbounded_String; -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Delete the wiki page as well as all its versions. procedure Delete (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); private -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page_Id : in ADO.Identifier); -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); type Wiki_Module is new AWA.Modules.Module with record Image_Prefix : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with ASF.Applications; with ADO; with ADO.Sessions; with AWA.Events; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Definition; with Security.Permissions; -- == Events == -- The <tt>wikis</tt> exposes a number of events which are posted when some action -- are performed at the service level. -- -- === wiki-create-page === -- This event is posted when a new wiki page is created. -- -- === wiki-create-content === -- This event is posted when a new wiki page content is created. Each time a wiki page is -- modified, a new wiki page content is created and this event is posted. -- package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; -- The configuration parameter that defines the image link prefix in rendered HTML content. PARAM_IMAGE_PREFIX : constant String := "image_prefix"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- Event posted when a new wiki page is created. package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page"); -- Event posted when a new wiki content is created. package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content"); -- Define the read wiki page counter. package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count"); package Wiki_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class); subtype Listener is Wiki_Lifecycle.Listener; -- The configuration parameter that defines a list of wiki page ID to copy when a new -- wiki space is created. PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list"; -- Exception raised when a wiki page name is already used for the wiki space. Name_Used : exception; -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Wiki_Module; Props : in ASF.Applications.Config); -- Get the image prefix that was configured for the Wiki module. function Get_Image_Prefix (Module : in Wiki_Module) return Ada.Strings.Unbounded.Unbounded_String; -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Delete the wiki page as well as all its versions. procedure Delete (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Load the wiki page and its content. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier); -- Load the wiki page and its content from the wiki space Id and the page name. procedure Load_Page (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Wiki : in ADO.Identifier; Name : in String); -- Create a new wiki content for the wiki page. procedure Create_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); private -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page_Id : in ADO.Identifier); -- Copy the wiki page with its last version to the wiki space. procedure Copy_Page (Module : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class); -- Save a new wiki content for the wiki page. procedure Save_Wiki_Content (Model : in Wiki_Module; DB : in out ADO.Sessions.Master_Session; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class); type Wiki_Module is new AWA.Modules.Module with record Image_Prefix : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Wikis.Modules;
Declare the PARAM_IMAGE_PREFIX constant and Configure procedure
Declare the PARAM_IMAGE_PREFIX constant and Configure procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9a48b5a6f124eeb5ecd723febf7ac9fc4ffe178a
regtests/security-permissions-tests.adb
regtests/security-permissions-tests.adb
----------------------------------------------------------------------- -- Security-permissions-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; 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.Definition", Test_Define_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index (invalid name)", Test_Get_Invalid_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; -- ------------------------------ -- Test the permission created by the Definition package. -- ------------------------------ procedure Test_Define_Permission (T : in out Test) is Index : Permission_Index; begin Index := Get_Permission_Index ("admin"); T.Assert (P_Admin.Permission = Index, "Invalid permission for admin"); Index := Get_Permission_Index ("create"); T.Assert (P_Create.Permission = Index, "Invalid permission for create"); Index := Get_Permission_Index ("update"); T.Assert (P_Update.Permission = Index, "Invalid permission for update"); Index := Get_Permission_Index ("delete"); T.Assert (P_Delete.Permission = Index, "Invalid permission for delete"); T.Assert (P_Admin.Permission /= P_Create.Permission, "Admin or create permission invalid"); T.Assert (P_Admin.Permission /= P_Update.Permission, "Admin or update permission invalid"); T.Assert (P_Admin.Permission /= P_Delete.Permission, "Admin or delete permission invalid"); T.Assert (P_Create.Permission /= P_Update.Permission, "Create or update permission invalid"); T.Assert (P_Create.Permission /= P_Delete.Permission, "Create or delete permission invalid"); T.Assert (P_Update.Permission /= P_Delete.Permission, "Create or delete permission invalid"); end Test_Define_Permission; -- ------------------------------ -- Test Get_Permission on invalid permission name. -- ------------------------------ procedure Test_Get_Invalid_Permission (T : in out Test) is Index : Permission_Index; pragma Unreferenced (Index); begin Index := Get_Permission_Index ("invalid"); Util.Tests.Fail (T, "No exception raised by Get_Permission_Index for an invalid name"); exception when Invalid_Name => null; end Test_Get_Invalid_Permission; end Security.Permissions.Tests;
----------------------------------------------------------------------- -- Security-permissions-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; 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.Definition", Test_Define_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Get_Permission_Index (invalid name)", Test_Get_Invalid_Permission'Access); Caller.Add_Test (Suite, "Test Security.Permissions.Add_Permission (Set)", Test_Add_Permission_Set'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; -- ------------------------------ -- Test the permission created by the Definition package. -- ------------------------------ procedure Test_Define_Permission (T : in out Test) is Index : Permission_Index; begin Index := Get_Permission_Index ("admin"); T.Assert (P_Admin.Permission = Index, "Invalid permission for admin"); Index := Get_Permission_Index ("create"); T.Assert (P_Create.Permission = Index, "Invalid permission for create"); Index := Get_Permission_Index ("update"); T.Assert (P_Update.Permission = Index, "Invalid permission for update"); Index := Get_Permission_Index ("delete"); T.Assert (P_Delete.Permission = Index, "Invalid permission for delete"); T.Assert (P_Admin.Permission /= P_Create.Permission, "Admin or create permission invalid"); T.Assert (P_Admin.Permission /= P_Update.Permission, "Admin or update permission invalid"); T.Assert (P_Admin.Permission /= P_Delete.Permission, "Admin or delete permission invalid"); T.Assert (P_Create.Permission /= P_Update.Permission, "Create or update permission invalid"); T.Assert (P_Create.Permission /= P_Delete.Permission, "Create or delete permission invalid"); T.Assert (P_Update.Permission /= P_Delete.Permission, "Create or delete permission invalid"); end Test_Define_Permission; -- ------------------------------ -- Test Get_Permission on invalid permission name. -- ------------------------------ procedure Test_Get_Invalid_Permission (T : in out Test) is Index : Permission_Index; pragma Unreferenced (Index); begin Index := Get_Permission_Index ("invalid"); Util.Tests.Fail (T, "No exception raised by Get_Permission_Index for an invalid name"); exception when Invalid_Name => null; end Test_Get_Invalid_Permission; -- ------------------------------ -- Test operations on the Permission_Index_Set. -- ------------------------------ procedure Test_Add_Permission_Set (T : in out Test) is Set : Permission_Index_Set := EMPTY_SET; begin T.Assert (not Has_Permission (Set, P_Update.Permission), "The update permission is not in the set"); Add_Permission (Set, P_Update.Permission); T.Assert (Has_Permission (Set, P_Update.Permission), "The update permission is in the set"); end Test_Add_Permission_Set; end Security.Permissions.Tests;
Implement the Test_Add_Permission_Set unit test to check the Permission_Index_Set
Implement the Test_Add_Permission_Set unit test to check the Permission_Index_Set
Ada
apache-2.0
stcarrez/ada-security
608d965fb9fc0460432dbd54f03fda7a5ea0ef95
src/natools-cron.adb
src/natools-cron.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- IMPLEMENTATION NOTE: -- -- In case of synchronized callbacks (same Origin and Period), there is a -- -- collision on the internal map key. Since it is not expected to happen -- -- often, a simple but not-so-efficient solution is used: -- -- When a collision is encountered, the callback is replaced by an -- -- Event_List callback seeded with the existing callback and the new one. -- -- When removing a callback, if it's not found directly, and second linear -- -- is performed, looking for Event_List objects and removing it from them. -- ------------------------------------------------------------------------------ package body Natools.Cron is function Create_Event_List (Ref_1, Ref_2 : Callback_Refs.Reference) return Callback_Refs.Reference; -- Create an Event_List object containing Ref_1 and Ref_2, -- and return a reference to it. ------------------------ -- Helper Subprograms -- ------------------------ function "<" (Left, Right : Periodic_Time) return Boolean is use type Ada.Calendar.Time; begin return Left.Origin < Right.Origin or else (Left.Origin = Right.Origin and then Left.Period < Right.Period); end "<"; function Create_Event_List (Ref_1, Ref_2 : Callback_Refs.Reference) return Callback_Refs.Reference is function Create return Callback'Class; function Create return Callback'Class is Result : Event_List; begin Result.Append (Ref_1); Result.Append (Ref_2); return Result; end Create; begin return Callback_Refs.Create (Create'Access); end Create_Event_List; ---------------------- -- Public Interface -- ---------------------- function Create (Time : in Periodic_Time; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Time, Callback); end return; end Create; function Create (Period : in Duration; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Period, Callback); end return; end Create; procedure Set (Self : in out Cron_Entry; Time : in Periodic_Time; Callback : in Cron.Callback'Class) is function Create return Cron.Callback'Class; function Create return Cron.Callback'Class is begin return Callback; end Create; begin Self.Reset; Self.Callback.Replace (Create'Access); Database.Insert (Time, Self.Callback); end Set; procedure Set (Self : in out Cron_Entry; Period : in Duration; Callback : in Cron.Callback'Class) is begin Set (Self, (Ada.Calendar.Clock, Period), Callback); end Set; overriding procedure Finalize (Object : in out Cron_Entry) is begin if not Object.Callback.Is_Empty then Object.Reset; end if; end Finalize; procedure Reset (Self : in out Cron_Entry) is begin if not Self.Callback.Is_Empty then Database.Remove (Self.Callback); Self.Callback.Reset; end if; end Reset; ------------------------ -- Protected Database -- ------------------------ protected body Database is procedure Insert (Time : in Periodic_Time; Callback : in Callback_Refs.Reference) is use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Actual_Time : Periodic_Time := Time; begin while Actual_Time.Origin < Now loop Actual_Time.Origin := Actual_Time.Origin + Actual_Time.Period; end loop; if Map.Is_Empty then if Global_Worker /= null and then Global_Worker.all'Terminated then Unchecked_Free (Global_Worker); end if; if Global_Worker = null then Global_Worker := new Worker; end if; else if Actual_Time < Map.First_Key then First_Changed := True; end if; end if; declare Position : Entry_Maps.Cursor; Inserted : Boolean; Previous : Callback_Refs.Reference; begin Map.Insert (Actual_Time, Callback, Position, Inserted); if not Inserted then Previous := Entry_Maps.Element (Position); if Previous.Update.Data.all in Event_List then Append (Event_List (Previous.Update.Data.all), Callback); else Map.Replace_Element (Position, Create_Event_List (Previous, Callback)); end if; end if; end; end Insert; procedure Remove (Callback : in Callback_Refs.Reference) is use type Callback_Refs.Reference; Cursor : Entry_Maps.Cursor := Map.First; Is_First : Boolean := True; begin while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor) = Callback then Map.Delete (Cursor); if Is_First then First_Changed := True; end if; return; end if; Entry_Maps.Next (Cursor); Is_First := False; end loop; Is_First := True; Cursor := Map.First; while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor).Update.Data.all in Event_List then declare Mutator : constant Callback_Refs.Mutator := Entry_Maps.Element (Cursor).Update; List : Event_List renames Event_List (Mutator.Data.all); Removed : Boolean; begin List.Remove (Callback, Removed); if Removed then if List.Is_Empty then Map.Delete (Cursor); if Is_First then First_Changed := True; end if; end if; return; end if; end; end if; Entry_Maps.Next (Cursor); Is_First := False; end loop; end Remove; procedure Update (Callback : in Callback_Refs.Reference) is use type Callback_Refs.Reference; Cursor : Entry_Maps.Cursor := Map.First; begin Search : while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor) = Callback then declare Old_Time : constant Periodic_Time := Entry_Maps.Key (Cursor); begin Map.Delete (Cursor); Insert (Old_Time, Callback); end; exit Search; end if; Entry_Maps.Next (Cursor); end loop Search; end Update; procedure Get_First (Time : out Periodic_Time; Callback : out Callback_Refs.Reference) is Cursor : constant Entry_Maps.Cursor := Map.First; begin if Entry_Maps.Has_Element (Cursor) then Time := Entry_Maps.Key (Cursor); Callback := Entry_Maps.Element (Cursor); else Callback := Callback_Refs.Null_Reference; end if; First_Changed := False; end Get_First; entry Update_Notification when First_Changed is begin null; end Update_Notification; end Database; ----------------- -- Worker Task -- ----------------- task body Worker is Time : Periodic_Time; Callback : Callback_Refs.Reference; Waiting : Boolean; begin Main : loop Waiting := True; Wait_Loop : while Waiting loop Database.Get_First (Time, Callback); exit Main when Callback.Is_Empty; select Database.Update_Notification; or delay until Time.Origin; Waiting := False; end select; end loop Wait_Loop; Callback.Update.Data.Run; Database.Update (Callback); end loop Main; end Worker; ---------------- -- Event List -- ---------------- overriding procedure Run (Self : in out Event_List) is begin for Ref of Self.List loop Ref.Update.Data.Run; end loop; end Run; procedure Append (Self : in out Event_List; Ref : in Callback_Refs.Reference) is begin Self.List.Append (Ref); end Append; procedure Remove (Self : in out Event_List; Ref : in Callback_Refs.Reference; Removed : out Boolean) is use type Callback_Refs.Reference; Cursor : Event_Lists.Cursor := Self.List.First; begin Removed := False; while Event_Lists.Has_Element (Cursor) loop if Event_Lists.Element (Cursor) = Ref then Self.List.Delete (Cursor); Removed := True; return; end if; Event_Lists.Next (Cursor); end loop; end Remove; function Is_Empty (Self : Event_List) return Boolean is begin return Self.List.Is_Empty; end Is_Empty; end Natools.Cron;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- IMPLEMENTATION NOTE: -- -- In case of synchronized callbacks (same Origin and Period), there is a -- -- collision on the internal map key. Since it is not expected to happen -- -- often, a simple but not-so-efficient solution is used: -- -- When a collision is encountered, the callback is replaced by an -- -- Event_List callback seeded with the existing callback and the new one. -- -- When removing a callback, if it's not found directly, and second linear -- -- is performed, looking for Event_List objects and removing it from them. -- ------------------------------------------------------------------------------ package body Natools.Cron is function Create_Event_List (Ref_1, Ref_2 : Callback_Refs.Reference) return Callback_Refs.Reference; -- Create an Event_List object containing Ref_1 and Ref_2, -- and return a reference to it. ------------------------ -- Helper Subprograms -- ------------------------ function "<" (Left, Right : Periodic_Time) return Boolean is use type Ada.Calendar.Time; begin return Left.Origin < Right.Origin or else (Left.Origin = Right.Origin and then Left.Period < Right.Period); end "<"; function Create_Event_List (Ref_1, Ref_2 : Callback_Refs.Reference) return Callback_Refs.Reference is function Create return Callback'Class; function Create return Callback'Class is Result : Event_List; begin Result.Append (Ref_1); Result.Append (Ref_2); return Result; end Create; begin return Callback_Refs.Create (Create'Access); end Create_Event_List; ---------------------- -- Public Interface -- ---------------------- function Create (Time : in Periodic_Time; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Time, Callback); end return; end Create; function Create (Period : in Duration; Callback : in Cron.Callback'Class) return Cron_Entry is begin return Result : Cron_Entry do Result.Set (Period, Callback); end return; end Create; procedure Set (Self : in out Cron_Entry; Time : in Periodic_Time; Callback : in Cron.Callback'Class) is function Create return Cron.Callback'Class; function Create return Cron.Callback'Class is begin return Callback; end Create; begin Self.Reset; Self.Callback.Replace (Create'Access); Database.Insert (Time, Self.Callback); end Set; procedure Set (Self : in out Cron_Entry; Period : in Duration; Callback : in Cron.Callback'Class) is begin Set (Self, (Ada.Calendar.Clock, Period), Callback); end Set; overriding procedure Finalize (Object : in out Cron_Entry) is begin if not Object.Callback.Is_Empty then Object.Reset; end if; end Finalize; procedure Reset (Self : in out Cron_Entry) is begin if not Self.Callback.Is_Empty then Database.Remove (Self.Callback); Self.Callback.Reset; end if; end Reset; ------------------------ -- Protected Database -- ------------------------ protected body Database is procedure Insert (Time : in Periodic_Time; Callback : in Callback_Refs.Reference) is use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Actual_Time : Periodic_Time := Time; begin if Actual_Time.Period > 0.0 then while Actual_Time.Origin < Now loop Actual_Time.Origin := Actual_Time.Origin + Actual_Time.Period; end loop; end if; if Map.Is_Empty then if Global_Worker /= null and then Global_Worker.all'Terminated then Unchecked_Free (Global_Worker); end if; if Global_Worker = null then Global_Worker := new Worker; end if; else if Actual_Time < Map.First_Key then First_Changed := True; end if; end if; declare Position : Entry_Maps.Cursor; Inserted : Boolean; Previous : Callback_Refs.Reference; begin Map.Insert (Actual_Time, Callback, Position, Inserted); if not Inserted then Previous := Entry_Maps.Element (Position); if Previous.Update.Data.all in Event_List then Append (Event_List (Previous.Update.Data.all), Callback); else Map.Replace_Element (Position, Create_Event_List (Previous, Callback)); end if; end if; end; end Insert; procedure Remove (Callback : in Callback_Refs.Reference) is use type Callback_Refs.Reference; Cursor : Entry_Maps.Cursor := Map.First; Is_First : Boolean := True; begin while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor) = Callback then Map.Delete (Cursor); if Is_First then First_Changed := True; end if; return; end if; Entry_Maps.Next (Cursor); Is_First := False; end loop; Is_First := True; Cursor := Map.First; while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor).Update.Data.all in Event_List then declare Mutator : constant Callback_Refs.Mutator := Entry_Maps.Element (Cursor).Update; List : Event_List renames Event_List (Mutator.Data.all); Removed : Boolean; begin List.Remove (Callback, Removed); if Removed then if List.Is_Empty then Map.Delete (Cursor); if Is_First then First_Changed := True; end if; end if; return; end if; end; end if; Entry_Maps.Next (Cursor); Is_First := False; end loop; end Remove; procedure Update (Callback : in Callback_Refs.Reference) is use type Callback_Refs.Reference; Cursor : Entry_Maps.Cursor := Map.First; begin Search : while Entry_Maps.Has_Element (Cursor) loop if Entry_Maps.Element (Cursor) = Callback then declare Old_Time : constant Periodic_Time := Entry_Maps.Key (Cursor); begin Map.Delete (Cursor); if Old_Time.Period > 0.0 then Insert (Old_Time, Callback); end if; end; exit Search; end if; Entry_Maps.Next (Cursor); end loop Search; end Update; procedure Get_First (Time : out Periodic_Time; Callback : out Callback_Refs.Reference) is Cursor : constant Entry_Maps.Cursor := Map.First; begin if Entry_Maps.Has_Element (Cursor) then Time := Entry_Maps.Key (Cursor); Callback := Entry_Maps.Element (Cursor); else Callback := Callback_Refs.Null_Reference; end if; First_Changed := False; end Get_First; entry Update_Notification when First_Changed is begin null; end Update_Notification; end Database; ----------------- -- Worker Task -- ----------------- task body Worker is Time : Periodic_Time; Callback : Callback_Refs.Reference; Waiting : Boolean; begin Main : loop Waiting := True; Wait_Loop : while Waiting loop Database.Get_First (Time, Callback); exit Main when Callback.Is_Empty; select Database.Update_Notification; or delay until Time.Origin; Waiting := False; end select; end loop Wait_Loop; Callback.Update.Data.Run; Database.Update (Callback); end loop Main; end Worker; ---------------- -- Event List -- ---------------- overriding procedure Run (Self : in out Event_List) is begin for Ref of Self.List loop Ref.Update.Data.Run; end loop; end Run; procedure Append (Self : in out Event_List; Ref : in Callback_Refs.Reference) is begin Self.List.Append (Ref); end Append; procedure Remove (Self : in out Event_List; Ref : in Callback_Refs.Reference; Removed : out Boolean) is use type Callback_Refs.Reference; Cursor : Event_Lists.Cursor := Self.List.First; begin Removed := False; while Event_Lists.Has_Element (Cursor) loop if Event_Lists.Element (Cursor) = Ref then Self.List.Delete (Cursor); Removed := True; return; end if; Event_Lists.Next (Cursor); end loop; end Remove; function Is_Empty (Self : Event_List) return Boolean is begin return Self.List.Is_Empty; end Is_Empty; end Natools.Cron;
use non-positive periods to mean non-repeating events
cron: use non-positive periods to mean non-repeating events
Ada
isc
faelys/natools
912735aa2891d570a2aa2b8f27efdf62a7d6bfa3
matp/src/mat-expressions.adb
matp/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Frames; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); Resolver : Resolver_Type_Access; -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; Region : MAT.Memory.Region_Info; begin if Resolver /= null then case Kind is when INSIDE_REGION | INSIDE_DIRECT_REGION => Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name)); when others => Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name)); end case; end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_HAS_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Event_Id_Type; Max : in MAT.Events.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Create an expression node to keep allocation events which don't have any associated free. -- ------------------------------ function Create_No_Free return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NO_FREE); return Result; end Create_No_Free; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Event); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Event_Id_Type; use type MAT.Events.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when N_IN_FUNC => return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String; Resolver : in Resolver_Type_Access) return Expression_Type is begin MAT.Expressions.Resolver := Resolver; return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Frames; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); Resolver : Resolver_Type_Access; -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; Region : MAT.Memory.Region_Info; begin if Resolver /= null then case Kind is when INSIDE_REGION | INSIDE_DIRECT_REGION => Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name)); when others => Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name)); end case; end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_HAS_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Event_Id_Type; Max : in MAT.Events.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Create an expression node to keep allocation events which don't have any associated free. -- ------------------------------ function Create_No_Free return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NO_FREE); return Result; end Create_No_Free; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Event); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when N_IN_FUNC => return MAT.Frames.In_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Event_Id_Type; use type MAT.Events.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when N_IN_FUNC => return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String; Resolver : in Resolver_Type_Access) return Expression_Type is begin MAT.Expressions.Resolver := Resolver; return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Fix the Is_Selected function on a memory slot to support the N_IN_FUNC and N_IN_FUNC_DIRECT selections
Fix the Is_Selected function on a memory slot to support the N_IN_FUNC and N_IN_FUNC_DIRECT selections
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7ad8a9fdc96b319f706bcb5c246c566eaed242ca
src/wiki-strings.ads
src/wiki-strings.ads
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Hash; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Ada.Strings.Wide_Wide_Fixed; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; 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; Output_BOM : in Boolean := False) return String renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode; 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.Strings.UTF_Encoding.Wide_Wide_Strings.Decode; function Hash (S : in WString) return Ada.Containers.Hash_Type renames Ada.Strings.Wide_Wide_Hash; 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;
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Hash; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Ada.Strings.Wide_Wide_Fixed; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; 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; Output_BOM : in Boolean := False) return String renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode; 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.Strings.UTF_Encoding.Wide_Wide_Strings.Decode; function Hash (S : in WString) return Ada.Containers.Hash_Type renames Ada.Strings.Wide_Wide_Hash; 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; function Element (Source : in BString; Position : in Positive) return WChar renames Wide_Wide_Builders.Element; -- Search for the first occurrence of the character in the builder and -- starting after the from index. Returns the index of the first occurence or 0. function Index (Source : in BString; Char : in WChar; From : in Positive := 1) return Natural; end Wiki.Strings;
Add the Element and Index operations
Add the Element and Index operations
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c0f5b78a2e27b0cff2dbfd24a69529b356ccc3e3
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. -- overriding -- procedure Include_Definition (Context : in out Facelet_Context; -- Name : in Ada.Strings.Unbounded.Unbounded_String; -- Parent : in UIComponent_Access); -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ -- overriding -- procedure Include_Definition (Context : in out Facelet_Context; -- Name : in Ada.Strings.Unbounded.Unbounded_String; -- Parent : in UIComponent_Access) is -- -- use ASF.Views; -- -- Tree : Facelets.Facelet; -- begin -- Facelets.Find_Facelet (Factory => Context.Facelets.all, -- Name => Ada.Strings.Unbounded.To_String (Name), -- Result => Tree); -- -- Facelets.Build_View (View => Tree, -- Context => Context, -- Root => Parent); -- end Include_Definition; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); if Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; -- ------------------------------ -- Register a module -- ------------------------------ procedure Register_Module (Handler : in out View_Handler; Module : in ASF.Modules.Module_Access) is use Ada.Strings.Unbounded; Name : constant String := Module.Get_Name; URI : constant String := Module.Get_URI; Def : constant String := To_String (Handler.Paths) & "/" & URI; Dir : constant String := Module.Get_Config (Name & ".web.dir", Def); begin ASF.Views.Facelets.Register_Module (Handler.Facelets, URI, Dir); end Register_Module; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- 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 Ada.Strings.Fixed; with Util.Files; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Responses; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. -- overriding -- procedure Include_Definition (Context : in out Facelet_Context; -- Name : in Ada.Strings.Unbounded.Unbounded_String; -- Parent : in UIComponent_Access); -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ -- overriding -- procedure Include_Definition (Context : in out Facelet_Context; -- Name : in Ada.Strings.Unbounded.Unbounded_String; -- Parent : in UIComponent_Access) is -- -- use ASF.Views; -- -- Tree : Facelets.Facelet; -- begin -- Facelets.Find_Facelet (Factory => Context.Facelets.all, -- Name => Ada.Strings.Unbounded.To_String (Name), -- Result => Tree); -- -- Facelets.Build_View (View => Tree, -- Context => Context, -- Root => Parent); -- end Include_Definition; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then To_String (Handler.View_Ext) = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); if Facelets.Is_Null (Tree) then Context.Get_Response.Send_Error (ASF.Responses.SC_NOT_FOUND); Context.Response_Completed; return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; -- ------------------------------ -- Register a module -- ------------------------------ procedure Register_Module (Handler : in out View_Handler; Module : in ASF.Modules.Module_Access) is use Ada.Strings.Unbounded; Name : constant String := Module.Get_Name; URI : constant String := Module.Get_URI; Def : constant String := Util.Files.Compose_Path (To_String (Handler.Paths), URI); Dir : constant String := Module.Get_Config (Name & ".web.dir", Def); begin ASF.Views.Facelets.Register_Module (Handler.Facelets, URI, Dir); end Register_Module; end ASF.Applications.Views;
Use Compose_Path to create the module specific search path
Use Compose_Path to create the module specific search path
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
29c606117efc8553c43bade95dd0b89d1d965726
src/asf-navigations-render.adb
src/asf-navigations-render.adb
----------------------------------------------------------------------- -- asf-navigations-render -- Navigator to render a page -- 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.Exceptions; with Util.Log.Loggers; with ASF.Components.Root; package body ASF.Navigations.Render is use Ada.Exceptions; use Util.Log; use ASF.Applications; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Navigations.Render"); -- ------------------------------ -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. -- ------------------------------ overriding procedure Navigate (Controller : in Render_Navigator; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Name : constant String := To_String (Controller.View_Name); View : Components.Root.UIViewRoot; begin Log.Debug ("Navigate to view {0}", Name); Controller.View_Handler.Create_View (Name, Context, View); Context.Set_View_Root (View); exception when E : others => Log.Error ("Error when navigating to view {0}: {1}: {2}", Name, Exception_Name (E), Exception_Message (E)); raise; end Navigate; -- ------------------------------ -- Create a navigation case to render a view. -- ------------------------------ function Create_Render_Navigator (To_View : in String) return Navigation_Access is Result : constant Render_Navigator_Access := new Render_Navigator; begin Result.View_Name := To_Unbounded_String (To_View); return Result.all'Access; end Create_Render_Navigator; end ASF.Navigations.Render;
----------------------------------------------------------------------- -- asf-navigations-render -- Navigator to render a page -- Copyright (C) 2010, 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with ASF.Components.Root; package body ASF.Navigations.Render is use Ada.Exceptions; use ASF.Applications; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Navigations.Render"); -- ------------------------------ -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. -- ------------------------------ overriding procedure Navigate (Controller : in Render_Navigator; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is View : Components.Root.UIViewRoot; begin Log.Debug ("Navigate to view {0}", Controller.View_Name); if Controller.Status /= 0 then Context.Get_Response.Set_Status (Controller.Status); end if; Controller.View_Handler.Create_View (Controller.View_Name, Context, View); Context.Set_View_Root (View); exception when E : others => Log.Error ("Error when navigating to view {0}: {1}: {2}", Controller.View_Name, Exception_Name (E), Exception_Message (E)); raise; end Navigate; -- ------------------------------ -- Create a navigation case to render a view. -- ------------------------------ function Create_Render_Navigator (To_View : in String; Status : in Natural) return Navigation_Access is Result : constant Render_Navigator_Access := new Render_Navigator '(Len => To_View'Length, Status => Status, View_Name => To_View, others => <>); begin return Result.all'Access; end Create_Render_Navigator; end ASF.Navigations.Render;
Change the Create_Render_Navigator to store the status parameter and the view name as a string Update Navigate operation to change the response status if it was set
Change the Create_Render_Navigator to store the status parameter and the view name as a string Update Navigate operation to change the response status if it was set
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
ed72ef2ff31f2df47154ccbc2967c088ba985596
regtests/security-permissions-tests.ads
regtests/security-permissions-tests.ads
----------------------------------------------------------------------- -- 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; package Security.Permissions.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Add_Permission and Get_Permission_Index procedure Test_Add_Permission (T : in out Test); -- Test Create_Role and Get_Role_Name procedure Test_Create_Role (T : in out Test); -- Test Has_Permission procedure Test_Has_Permission (T : in out Test); -- Test reading policy files procedure Test_Read_Policy (T : in out Test); -- Test reading policy files and using the <role-permission> controller procedure Test_Role_Policy (T : in out Test); -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String); type Test_Principal is new Principal with record Name : Util.Strings.String_Ref; Roles : Role_Map := (others => False); end record; -- Returns true if the given permission is stored in the user principal. function Has_Role (User : in Test_Principal; Role : in Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Test_Principal) return String; end Security.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; package Security.Permissions.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Add_Permission and Get_Permission_Index procedure Test_Add_Permission (T : in out Test); end Security.Permissions.Tests;
Remove the policy specific unit tests
Remove the policy specific unit tests
Ada
apache-2.0
stcarrez/ada-security
0671573db72c7a1b3aa7e0d6dc7bd67f364650f3
src/gl/implementation/gl-context.adb
src/gl/implementation/gl-context.adb
-- Copyright (c) 2013 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Strings; with GL.API; with GL.Enums.Getter; with GL.Errors; package body GL.Context is function Major_Version return Int is Result : aliased Int; begin API.Get_Integer (Enums.Getter.Major_Version, Result'Access); Raise_Exception_On_OpenGL_Error; return Result; end Major_Version; function Minor_Version return Int is Result : aliased Int; begin API.Get_Integer (Enums.Getter.Minor_Version, Result'Access); Raise_Exception_On_OpenGL_Error; return Result; end Minor_Version; function Version_String return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Version)); end Version_String; function Vendor return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Vendor)); end Vendor; function Renderer return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Renderer)); end Renderer; function Extensions return String_List is use Ada.Strings.Unbounded; use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Extensions, Count'Access); Raise_Exception_On_OpenGL_Error; pragma Assert (API.Get_Error = Errors.No_Error); -- We are on OpenGL 3 return List : String_List (1 .. Positive (Count)) do for I in List'Range loop List (I) := To_Unbounded_String (C.Strings.Value (API.Get_String_I (Enums.Getter.Extensions, UInt (I - 1)))); end loop; end return; end Extensions; function Has_Extension (Name : String) return Boolean is use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Extensions, Count'Access); Raise_Exception_On_OpenGL_Error; pragma Assert (API.Get_Error = Errors.No_Error); -- We are on OpenGL 3 for I in 1 .. Count loop declare Extension : constant String := C.Strings.Value (API.Get_String_I (Enums.Getter.Extensions, UInt (I - 1))); begin if Extension = Name then return True; end if; end; end loop; return False; end Has_Extension; function Primary_Shading_Language_Version return String is Result : constant String := C.Strings.Value (API.Get_String (Enums.Getter.Shading_Language_Version)); begin Raise_Exception_On_OpenGL_Error; return Result; end Primary_Shading_Language_Version; function Supported_Shading_Language_Versions return String_List is use Ada.Strings.Unbounded; use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Shading_Language_Versions, Count'Access); if API.Get_Error = Errors.Invalid_Enum then raise Feature_Not_Supported_Exception; end if; return List : String_List (1 .. Positive (Count)) do for I in List'Range loop List (I) := To_Unbounded_String (C.Strings.Value (API.Get_String_I ( Enums.Getter.Shading_Language_Version, UInt (I)))); end loop; end return; end Supported_Shading_Language_Versions; function Supports_Shading_Language_Version (Name : String) return Boolean is Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Shading_Language_Versions, Count'Access); Raise_Exception_On_OpenGL_Error; for I in 1 .. Count loop if C.Strings.Value (API.Get_String_I (Enums.Getter.Shading_Language_Version, UInt (I))) = Name then return True; end if; end loop; return False; end Supports_Shading_Language_Version; end GL.Context;
-- Copyright (c) 2013 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Strings; with GL.API; with GL.Enums.Getter; with GL.Errors; package body GL.Context is function Major_Version return Int is Result : aliased Int; begin API.Get_Integer (Enums.Getter.Major_Version, Result'Access); Raise_Exception_On_OpenGL_Error; return Result; end Major_Version; function Minor_Version return Int is Result : aliased Int; begin API.Get_Integer (Enums.Getter.Minor_Version, Result'Access); Raise_Exception_On_OpenGL_Error; return Result; end Minor_Version; function Version_String return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Version)); end Version_String; function Vendor return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Vendor)); end Vendor; function Renderer return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Renderer)); end Renderer; function Extensions return String_List is use Ada.Strings.Unbounded; use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Extensions, Count'Access); Raise_Exception_On_OpenGL_Error; pragma Assert (API.Get_Error = Errors.No_Error); -- We are on OpenGL 3 return List : String_List (1 .. Positive (Count)) do for I in List'Range loop List (I) := To_Unbounded_String (C.Strings.Value (API.Get_String_I (Enums.Getter.Extensions, UInt (I - 1)))); end loop; end return; end Extensions; function Has_Extension (Name : String) return Boolean is use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Extensions, Count'Access); Raise_Exception_On_OpenGL_Error; pragma Assert (API.Get_Error = Errors.No_Error); -- We are on OpenGL 3 for I in 1 .. Count loop declare Extension : constant String := C.Strings.Value (API.Get_String_I (Enums.Getter.Extensions, UInt (I - 1))); begin if Extension = Name then return True; end if; end; end loop; return False; end Has_Extension; function Primary_Shading_Language_Version return String is Result : constant String := C.Strings.Value (API.Get_String (Enums.Getter.Shading_Language_Version)); begin Raise_Exception_On_OpenGL_Error; return Result; end Primary_Shading_Language_Version; function Supported_Shading_Language_Versions return String_List is use Ada.Strings.Unbounded; use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Shading_Language_Versions, Count'Access); if API.Get_Error = Errors.Invalid_Enum then raise Feature_Not_Supported_Exception; end if; return List : String_List (1 .. Positive (Count)) do for I in List'Range loop List (I) := To_Unbounded_String (C.Strings.Value (API.Get_String_I ( Enums.Getter.Shading_Language_Version, UInt (I - 1)))); end loop; end return; end Supported_Shading_Language_Versions; function Supports_Shading_Language_Version (Name : String) return Boolean is Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Shading_Language_Versions, Count'Access); Raise_Exception_On_OpenGL_Error; for I in 1 .. Count loop if C.Strings.Value (API.Get_String_I (Enums.Getter.Shading_Language_Version, UInt (I - 1))) = Name then return True; end if; end loop; return False; end Supports_Shading_Language_Version; end GL.Context;
Fix an off-by-one error in GL.Context
gl: Fix an off-by-one error in GL.Context Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
210e938a9b3dd4c7bb5532027d0091b9e0473bdc
awa/regtests/awa-blogs-services-tests.adb
awa/regtests/awa-blogs-services-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Module; with AWA.Users.Services.Tests.Helpers; package body AWA.Blogs.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; 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 AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); end Add_Tests; -- ------------------------------ -- Test creation of a user -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Users.Services.Tests.Helpers.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Module.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog", Result => Blog_Id); end Test_Create_Blog; end AWA.Blogs.Services.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with Util.Measures; with ADO; with ADO.Sessions; with ADO.SQL; with ADO.Objects; with Ada.Calendar; with Security.Contexts; with AWA.Services.Contexts; with AWA.Blogs.Module; with AWA.Users.Services.Tests.Helpers; package body AWA.Blogs.Services.Tests is use Util.Tests; use ADO; use ADO.Objects; 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 AWA.Blogs.Services.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post", Test_Create_Post'Access); end Add_Tests; -- ------------------------------ -- Test creation of a blog -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Users.Services.Tests.Helpers.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Module.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); end Test_Create_Blog; -- ------------------------------ -- Test creating and updating of a blog post -- ------------------------------ procedure Test_Create_Post (T : in out Test) is Manager : AWA.Blogs.Services.Blog_Service_Access; Blog_Id : ADO.Identifier; Post_Id : ADO.Identifier; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Users.Services.Tests.Helpers.Login (Context, Sec_Ctx, "[email protected]"); Manager := AWA.Blogs.Module.Get_Blog_Manager; Manager.Create_Blog (Workspace_Id => 0, Title => "My blog post", Result => Blog_Id); T.Assert (Blog_Id > 0, "Invalid blog identifier"); Manager.Create_Post (Blog_Id => Blog_Id, Title => "Testing blog title", URI => "testing-blog-title", Text => "The blog content", Result => Post_Id); T.Assert (Post_Id > 0, "Invalid post identifier"); Manager.Update_Post (Post_Id => Post_Id, Title => "New blog post title", Text => "The new post content"); Manager.Delete_Post (Post_Id => Post_Id); -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Update_Post (Post_Id => Post_Id, Title => "Something", Text => "Content"); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; -- Verify that a Not_Found exception is raised if the post was deleted. begin Manager.Delete_Post (Post_Id => Post_Id); T.Assert (False, "Exception Not_Found was not raised"); exception when Not_Found => null; end; end Test_Create_Post; end AWA.Blogs.Services.Tests;
Add unit test for post creation
Add unit test for post creation
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
d83f8369cbe5caaef18dce94930b73c8b3baba56
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Set_Reader_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Serialize.IO.XML; with GNAT.Regexp; package Security.Policies.Urls is NAME : constant String := "URL-Policy"; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Permissions.Permission with record URI : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Set_Reader_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); private -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; end record; end Security.Policies.Urls;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
Letractively/ada-security
20a334e67c2546f2e146ce2994f6cbafda381d34
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
awa/plugins/awa-blogs/src/awa-blogs-modules.adb
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with ADO.Sessions; with Ada.Calendar; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Blog); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with AWA.Modules.Get; with AWA.Modules.Beans; with AWA.Blogs.Beans; with AWA.Applications; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with ADO.Sessions; with Ada.Calendar; package body AWA.Blogs.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module"); package Register is new AWA.Modules.Beans (Module => Blog_Module, Module_Access => Blog_Module_Access); -- ------------------------------ -- Initialize the blog module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the blogs module"); -- Setup the resource bundles. App.Register ("blogMsg", "blogs"); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_Bean", Handler => AWA.Blogs.Beans.Create_Post_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Post_List_Bean", Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Admin_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Blog_Bean", Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Blogs.Beans.Status_List_Bean", Handler => AWA.Blogs.Beans.Create_Status_List'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the blog module instance associated with the current application. -- ------------------------------ function Get_Blog_Module return Blog_Module_Access is function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME); begin return Get; end Get_Blog_Module; -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Module; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; WS : AWA.Workspaces.Models.Workspace_Ref; begin Log.Info ("Creating blog {0} for user", Title); Ctx.Start; AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => WS); Blog.Set_Name (Title); Blog.Set_Workspace (WS); Blog.Set_Create_Date (Ada.Calendar.Clock); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Blog); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, Entity => Blog); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Set_Status (Status); Post.Set_Blog (Blog); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Comment : in Boolean; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); use type AWA.Blogs.Models.Post_Status_Type; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post); if Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null then Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Uri (URI); Post.Set_Status (Status); Post.Set_Allow_Comments (Comment); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Modules;
Set the post publication date when the post is published for the first time
Set the post publication date when the post is published for the first time
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
908ef3c56fd64e104d880061c92bdc7a4474b564
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, 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;
----------------------------------------------------------------------- -- 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, -- 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, UNDERLINE); 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;
Remove SYNTAX_MIX because it is not useful Add UNDERLINE as new format
Remove SYNTAX_MIX because it is not useful Add UNDERLINE as new format
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c5aa3876c0840730dee5e96154a40fe49e74bab0
src/ado-sessions-factory.ads
src/ado-sessions-factory.ads
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 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 ADO.Schemas.Entities; with ADO.Sequences; with ADO.Caches; with ADO.Sessions.Sources; -- === Session Factory === -- The session factory is the entry point to obtain a database session. -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. -- -- with ADO.Sessions.Factory; -- ... -- Sess_Factory : ADO.Sessions.Factory; -- -- The session factory can be initialized by using the <tt>Create</tt> operation and -- by giving a URI string that identifies the driver and the information to connect -- to the database. The session factory is created only once when the application starts. -- -- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test"); -- -- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or -- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session -- is returned. The session is released when the session variable is finalized. -- -- DB : ADO.Sessions.Session := Sess_Factory.Get_Session; -- -- The session factory is also responsible for maintaining some data that is shared by -- all the database connections. This includes: -- -- o the sequence generators used to allocate unique identifiers for database tables, -- o the entity cache, -- o some application specific global cache. -- package ADO.Sessions.Factory is pragma Elaborate_Body; ENTITY_CACHE_NAME : constant String := "entity_type"; -- ------------------------------ -- Session factory -- ------------------------------ type Session_Factory is tagged limited private; type Session_Factory_Access is access all Session_Factory'Class; -- Get a read-only session from the factory. function Get_Session (Factory : in Session_Factory) return Session; -- Get a read-write session from the factory. function Get_Master_Session (Factory : in Session_Factory) return Master_Session; -- Open a session procedure Open_Session (Factory : in out Session_Factory; Database : out Session); -- Open a session procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session); -- Create the session factory to connect to the database represented -- by the data source. procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source); -- Create the session factory to connect to the database identified -- by the URI. procedure Create (Factory : out Session_Factory; URI : in String); -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. function Get_Session (Proxy : in Session_Record_Access) return Session; private -- The session factory holds the necessary information to obtain a master or slave -- database connection. The sequence factory is shared by all sessions of the same -- factory (implementation is thread-safe). The factory also contains the entity type -- cache which is initialized when the factory is created. type Session_Factory is tagged limited record Source : ADO.Sessions.Sources.Data_Source; Sequences : Factory_Access := null; Seq_Factory : aliased ADO.Sequences.Factory; -- Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache; Entities : ADO.Sessions.Entity_Cache_Access := null; Cache : aliased ADO.Caches.Cache_Manager; Cache_Values : ADO.Caches.Cache_Manager_Access; end record; -- Initialize the sequence factory associated with the session factory. procedure Initialize_Sequences (Factory : in out Session_Factory); end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 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 ADO.Sequences; with ADO.Caches; with ADO.Sessions.Sources; -- === Session Factory === -- The session factory is the entry point to obtain a database session. -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. -- -- with ADO.Sessions.Factory; -- ... -- Sess_Factory : ADO.Sessions.Factory; -- -- The session factory can be initialized by using the <tt>Create</tt> operation and -- by giving a URI string that identifies the driver and the information to connect -- to the database. The session factory is created only once when the application starts. -- -- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test"); -- -- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or -- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session -- is returned. The session is released when the session variable is finalized. -- -- DB : ADO.Sessions.Session := Sess_Factory.Get_Session; -- -- The session factory is also responsible for maintaining some data that is shared by -- all the database connections. This includes: -- -- o the sequence generators used to allocate unique identifiers for database tables, -- o the entity cache, -- o some application specific global cache. -- package ADO.Sessions.Factory is pragma Elaborate_Body; ENTITY_CACHE_NAME : constant String := "entity_type"; -- ------------------------------ -- Session factory -- ------------------------------ type Session_Factory is tagged limited private; type Session_Factory_Access is access all Session_Factory'Class; -- Get a read-only session from the factory. function Get_Session (Factory : in Session_Factory) return Session; -- Get a read-write session from the factory. function Get_Master_Session (Factory : in Session_Factory) return Master_Session; -- Open a session procedure Open_Session (Factory : in out Session_Factory; Database : out Session); -- Open a session procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session); -- Create the session factory to connect to the database represented -- by the data source. procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source); -- Create the session factory to connect to the database identified -- by the URI. procedure Create (Factory : out Session_Factory; URI : in String); -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. function Get_Session (Proxy : in Session_Record_Access) return Session; private -- The session factory holds the necessary information to obtain a master or slave -- database connection. The sequence factory is shared by all sessions of the same -- factory (implementation is thread-safe). The factory also contains the entity type -- cache which is initialized when the factory is created. type Session_Factory is tagged limited record Source : ADO.Sessions.Sources.Data_Source; Sequences : Factory_Access := null; Seq_Factory : aliased ADO.Sequences.Factory; -- Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache; Entities : ADO.Sessions.Entity_Cache_Access := null; Cache : aliased ADO.Caches.Cache_Manager; Cache_Values : ADO.Caches.Cache_Manager_Access; end record; -- Initialize the sequence factory associated with the session factory. procedure Initialize_Sequences (Factory : in out Session_Factory); end ADO.Sessions.Factory;
Fix compilation warning detected by GNAT 2017
Fix compilation warning detected by GNAT 2017
Ada
apache-2.0
stcarrez/ada-ado
4233749489363a0760fd02fb21969e0e7200eb6b
awa/src/awa-permissions.ads
awa/src/awa-permissions.ads
----------------------------------------------------------------------- -- awa-permissions -- Permissions 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 Security.Permissions; with Security.Policies; with Util.Serialize.IO.XML; with ADO; -- == Introduction == -- The *AWA.Permissions* framework defines and controls the permissions used by an application -- to verify and grant access to the data and application service. The framework provides a -- set of services and API that helps an application in enforcing its specific permissions. -- Permissions are verified by a permission controller which uses the service context to -- have information about the user and other context. The framework allows to use different -- kinds of permission controllers. The `Entity_Controller` is the default permission -- controller which uses the database and an XML configuration to verify a permission. -- -- === Declaration === -- To be used in the application, the first step is to declare the permission. -- This is a static definition of the permission that will be used to ask to verify the -- permission. The permission is given a unique name that will be used in configuration files: -- -- package ACL_Create_Post is new Security.Permissions.Permission_ACL ("blog-create-post"); -- -- === Checking for a permission === -- A permission can be checked in Ada as well as in the presentation pages. -- This is done by using the `Check` procedure and the permission definition. This operation -- acts as a barrier: it does not return anything but returns normally if the permission is -- granted. If the permission is denied, it raises the `NO_PERMISSION` exception. -- -- Several `Check` operation exists. Some require not argument and some others need a context -- such as some entity identifier to perform the check. -- -- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, -- Entity => Blog_Id); -- -- === Configuring a permission === -- The *AWA.Permissions* framework supports a simple permission model -- The application configuration file must provide some information to help in checking the -- permission. The permission name is referenced by the `name` XML entity. The `entity-type` -- refers to the database entity (ie, the table) that the permission concerns. -- The `sql` XML entity represents the SQL statement that must be used to verify the permission. -- -- <entity-permission> -- <name>blog-create-post</name> -- <entity-type>blog</entity-type> -- <description>Permission to create a new post.</description> -- <sql> -- SELECT acl.id FROM acl -- WHERE acl.entity_type = :entity_type -- AND acl.user_id = :user_id -- AND acl.entity_id = :entity_id -- </sql> -- </entity-permission> -- -- === Adding a permission === -- Adding a permission means to create an `ACL` database record that links a given database -- entity to the user. This is done easily with the `Add_Permission` procedure: -- -- AWA.Permissions.Services.Add_Permission (Session => DB, -- User => User, -- Entity => Blog); -- -- == Data Model == -- @include Permission.hbm.xml -- -- == Queries == -- @include permissions.xml -- package AWA.Permissions is NAME : constant String := "Entity-Policy"; -- Exception raised by the <b>Check</b> procedure if the user does not have -- the permission. NO_PERMISSION : exception; type Permission_Type is (READ, WRITE); type Entity_Permission is new Security.Permissions.Permission with private; -- Verify that the permission represented by <b>Permission</b> is granted. -- procedure Check (Permission : in Security.Permissions.Permission_Index); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier); -- -- -- Get from the security context <b>Context</b> an identifier stored under the -- -- name <b>Name</b>. Returns NO_IDENTIFIER if the security context does not define -- -- such name or the value is not a valid identifier. -- function Get_Context (Context : in Security.Contexts.Security_Context'Class; -- Name : in String) return ADO.Identifier; private type Entity_Permission is new Security.Permissions.Permission with record Entity : ADO.Identifier; end record; type Entity_Policy is new Security.Policies.Policy with null record; type Entity_Policy_Access is access all Entity_Policy'Class; -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions 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 Security.Permissions; with Security.Policies; with Util.Serialize.IO.XML; with ADO; -- == Introduction == -- The *AWA.Permissions* framework defines and controls the permissions used by an application -- to verify and grant access to the data and application service. The framework provides a -- set of services and API that helps an application in enforcing its specific permissions. -- Permissions are verified by a permission controller which uses the service context to -- have information about the user and other context. The framework allows to use different -- kinds of permission controllers. The `Entity_Controller` is the default permission -- controller which uses the database and an XML configuration to verify a permission. -- -- === Declaration === -- To be used in the application, the first step is to declare the permission. -- This is a static definition of the permission that will be used to ask to verify the -- permission. The permission is given a unique name that will be used in configuration files: -- -- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); -- -- === Checking for a permission === -- A permission can be checked in Ada as well as in the presentation pages. -- This is done by using the `Check` procedure and the permission definition. This operation -- acts as a barrier: it does not return anything but returns normally if the permission is -- granted. If the permission is denied, it raises the `NO_PERMISSION` exception. -- -- Several `Check` operation exists. Some require not argument and some others need a context -- such as some entity identifier to perform the check. -- -- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, -- Entity => Blog_Id); -- -- === Configuring a permission === -- The *AWA.Permissions* framework supports a simple permission model -- The application configuration file must provide some information to help in checking the -- permission. The permission name is referenced by the `name` XML entity. The `entity-type` -- refers to the database entity (ie, the table) that the permission concerns. -- The `sql` XML entity represents the SQL statement that must be used to verify the permission. -- -- <entity-permission> -- <name>blog-create-post</name> -- <entity-type>blog</entity-type> -- <description>Permission to create a new post.</description> -- <sql> -- SELECT acl.id FROM acl -- WHERE acl.entity_type = :entity_type -- AND acl.user_id = :user_id -- AND acl.entity_id = :entity_id -- </sql> -- </entity-permission> -- -- === Adding a permission === -- Adding a permission means to create an `ACL` database record that links a given database -- entity to the user. This is done easily with the `Add_Permission` procedure: -- -- AWA.Permissions.Services.Add_Permission (Session => DB, -- User => User, -- Entity => Blog); -- -- == Data Model == -- @include Permission.hbm.xml -- -- == Queries == -- @include permissions.xml -- package AWA.Permissions is NAME : constant String := "Entity-Policy"; -- Exception raised by the <b>Check</b> procedure if the user does not have -- the permission. NO_PERMISSION : exception; type Permission_Type is (READ, WRITE); type Entity_Permission is new Security.Permissions.Permission with private; -- Verify that the permission represented by <b>Permission</b> is granted. -- procedure Check (Permission : in Security.Permissions.Permission_Index); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier); -- -- -- Get from the security context <b>Context</b> an identifier stored under the -- -- name <b>Name</b>. Returns NO_IDENTIFIER if the security context does not define -- -- such name or the value is not a valid identifier. -- function Get_Context (Context : in Security.Contexts.Security_Context'Class; -- Name : in String) return ADO.Identifier; private type Entity_Permission is new Security.Permissions.Permission with record Entity : ADO.Identifier; end record; type Entity_Policy is new Security.Policies.Policy with null record; type Entity_Policy_Access is access all Entity_Policy'Class; -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser); end AWA.Permissions;
Use the Permissions.Definition generic package
Use the Permissions.Definition generic package
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
d15e14f2a957939ffaf8747fdd0b523274c8dba6
src/security-auth-openid.ads
src/security-auth-openid.ads
----------------------------------------------------------------------- -- security-openid -- OpenID 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. ----------------------------------------------------------------------- -- === OpenID Configuration == -- The Open ID provider needs the following configuration parameters: -- -- openid.realm The OpenID realm parameter passed in the authentication URL. -- openid.callback_url The OpenID return_to parameter. -- private package Security.Auth.OpenID is -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is new Security.Auth.Manager with private; -- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt> -- and <tt>openid.callback_url</tt> parameters to configure the realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); -- 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. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding 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) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding 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); -- 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 type Manager is new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; end record; end Security.Auth.OpenID;
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == OpenID Configuration == -- The Open ID provider needs the following configuration parameters: -- -- openid.realm The OpenID realm parameter passed in the authentication URL. -- openid.callback_url The OpenID return_to parameter. -- private package Security.Auth.OpenID is -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is new Security.Auth.Manager with private; -- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt> -- and <tt>openid.callback_url</tt> parameters to configure the realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); -- 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. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding 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) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding 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); -- 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 type Manager is new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; end record; end Security.Auth.OpenID;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
cbf2ecdada2366b9089beecc399e45fd58c38639
src/util-properties-json.ads
src/util-properties-json.ads
----------------------------------------------------------------------- -- util-properties-json -- read json files into properties -- 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. ----------------------------------------------------------------------- -- The <tt>Util.Properties.JSON</tt> package provides operations to read a JSON -- content and put the result in a property manager. The JSON content is flattened -- into a set of name/value pairs. The JSON structure is reflected in the name. -- Example: -- -- { "id": "1", id -> 1 -- "info": { "name": "search", info.name -> search -- "count", "12", info.count -> 12 -- "data": { "value": "empty" }}, info.data -> empty -- "count": 1 info.count -> 1 -- } package Util.Properties.JSON is -- Parse the JSON content and put the flattened content in the property manager. procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class; Content : in String; Flatten_Separator : in String := "."); -- Read the JSON file into the property manager. -- The JSON content is flatten into Flatten the JSON content and add the properties. procedure Read_JSON (Manager : in out Util.Properties.Manager'Class; Path : in String; Flatten_Separator : in String := "."); end Util.Properties.JSON;
----------------------------------------------------------------------- -- util-properties-json -- read json files into properties -- 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. ----------------------------------------------------------------------- -- == Reading JSON property files == -- The `Util.Properties.JSON` package provides operations to read a JSON -- content and put the result in a property manager. The JSON content is flattened -- into a set of name/value pairs. The JSON structure is reflected in the name. -- Example: -- -- { "id": "1", id -> 1 -- "info": { "name": "search", info.name -> search -- "count", "12", info.count -> 12 -- "data": { "value": "empty" }}, info.data.value -> empty -- "count": 1 info.count -> 1 -- } -- -- To get the value of a JSON property, the user can use the flatten name. For example: -- -- Value : constant String := Props.Get ("info.data.value"); -- -- The default separator to construct a flatten name is the dot (`.`) but this can be -- changed easily when loading the JSON file by specifying the desired separator: -- -- Util.Properties.JSON.Read_JSON (Props, "config.json", "|"); -- -- Then, the property will be fetch by using: -- -- Value : constant String := Props.Get ("info|data|value"); -- package Util.Properties.JSON is -- Parse the JSON content and put the flattened content in the property manager. procedure Parse_JSON (Manager : in out Util.Properties.Manager'Class; Content : in String; Flatten_Separator : in String := "."); -- Read the JSON file into the property manager. -- The JSON content is flatten into Flatten the JSON content and add the properties. procedure Read_JSON (Manager : in out Util.Properties.Manager'Class; Path : in String; Flatten_Separator : in String := "."); end Util.Properties.JSON;
Document the JSON properties support
Document the JSON properties support
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b15daf195786e445bc301fe4576ef9983e8a3a16
mat/src/gtk/mat-consoles-gtkmat.adb
mat/src/gtk/mat-consoles-gtkmat.adb
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Gtk.Enums; with Gtk.Tree_View_Column; with Util.Log.Loggers; package body MAT.Consoles.Gtkmat is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Consoles.Gtkmat"); -- ------------------------------ -- Initialize the console to display the result in the Gtk frame. -- ------------------------------ procedure Initialize (Console : in out Console_Type; Frame : in Gtk.Frame.Gtk_Frame) is begin Gtk.Scrolled_Window.Gtk_New (Console.Scrolled); Gtk.Cell_Renderer_Text.Gtk_New (Console.Col_Text); Console.Scrolled.Set_Policy (Gtk.Enums.Policy_Always, Gtk.Enums.Policy_Always); Console.Frame := Frame; Console.Frame.Add (Console.Scrolled); Console.Col_Text.Ref; -- Console.Frame.Show_All; end Initialize; -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is begin null; end Notice; -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String) is begin null; end Error; -- Print the field value for the given field. overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is begin Log.Debug ("Field {0} - {1}", Field_Type'Image (Field), Value); Gtk.List_Store.Set (Console.List, Console.Current_Row, Console.Indexes (Field), Value); end Print_Field; -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is Pos : constant Positive := Console.Field_Count; begin Console.Indexes (Field) := Glib.Gint (Pos - 1); Console.Columns (Pos).Field := Field; Console.Columns (Pos).Title := Ada.Strings.Unbounded.To_Unbounded_String (Title); end Print_Title; -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); Console.Indexes := (others => 0); end Start_Title; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is use type Glib.Guint; use type Glib.Gint; use type Gtk.Tree_View.Gtk_Tree_View; use Gtk.List_Store; Types : Glib.GType_Array (0 .. Glib.Guint (Console.Field_Count) - 1) := (others => Glib.GType_String); Col : Gtk.Tree_View_Column.Gtk_Tree_View_Column; Num : Glib.Gint; begin Gtk.List_Store.Gtk_New (Console.List, Types); if Console.Tree /= null then Console.Tree.Destroy; end if; Gtk.Tree_View.Gtk_New (Console.Tree); for I in 1 .. Console.Field_Count loop Gtk.Tree_View_Column.Gtk_New (Col); Num := Console.Tree.Append_Column (Col); Col.Set_Sort_Column_Id (Glib.Gint (I) - 1); Col.Set_Title (Ada.Strings.Unbounded.To_String (Console.Columns (I).Title)); Col.Pack_Start (Console.Col_Text, True); Col.Set_Sizing (Gtk.Tree_View_Column.Tree_View_Column_Autosize); Col.Add_Attribute (Console.Col_Text, "text", Glib.Gint (I) - 1); end loop; Console.Tree.Set_Model (+Console.List); Console.Scrolled.Add (Console.Tree); Console.Scrolled.Show_All; end End_Title; -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type) is begin Console.List.Append (Console.Current_Row); end Start_Row; -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type) is begin null; end End_Row; end MAT.Consoles.Gtkmat;
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Gtk.Enums; with Gtk.Tree_View_Column; with Util.Log.Loggers; package body MAT.Consoles.Gtkmat is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Consoles.Gtkmat"); -- ------------------------------ -- Initialize the console to display the result in the Gtk frame. -- ------------------------------ procedure Initialize (Console : in out Console_Type; Frame : in Gtk.Frame.Gtk_Frame) is begin Gtk.Scrolled_Window.Gtk_New (Console.Scrolled); Gtk.Cell_Renderer_Text.Gtk_New (Console.Col_Text); Console.Scrolled.Set_Policy (Gtk.Enums.Policy_Always, Gtk.Enums.Policy_Always); Console.Frame := Frame; Console.Frame.Add (Console.Scrolled); Console.Col_Text.Ref; -- Console.Frame.Show_All; end Initialize; -- Report a notice message. overriding procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is begin null; end Notice; -- Report an error message. overriding procedure Error (Console : in out Console_Type; Message : in String) is begin null; end Error; -- 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) is begin Log.Debug ("Field {0} - {1}", Field_Type'Image (Field), Value); Gtk.List_Store.Set (Console.List, Console.Current_Row, Console.Indexes (Field), Value); end Print_Field; -- Print the title for the given field. overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is Pos : constant Positive := Console.Field_Count; begin Console.Indexes (Field) := Glib.Gint (Pos - 1); Console.Columns (Pos).Field := Field; Console.Columns (Pos).Title := Ada.Strings.Unbounded.To_Unbounded_String (Title); end Print_Title; -- Start a new title in a report. overriding procedure Start_Title (Console : in out Console_Type) is begin Console.Field_Count := 0; Console.Sizes := (others => 0); Console.Cols := (others => 1); Console.Indexes := (others => 0); end Start_Title; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is use type Glib.Guint; use type Glib.Gint; use type Gtk.Tree_View.Gtk_Tree_View; use Gtk.List_Store; Types : Glib.GType_Array (0 .. Glib.Guint (Console.Field_Count) - 1) := (others => Glib.GType_String); Col : Gtk.Tree_View_Column.Gtk_Tree_View_Column; Num : Glib.Gint; begin Gtk.List_Store.Gtk_New (Console.List, Types); if Console.Tree /= null then Console.Tree.Destroy; end if; Gtk.Tree_View.Gtk_New (Console.Tree); for I in 1 .. Console.Field_Count loop Gtk.Tree_View_Column.Gtk_New (Col); Num := Console.Tree.Append_Column (Col); Col.Set_Sort_Column_Id (Glib.Gint (I) - 1); Col.Set_Title (Ada.Strings.Unbounded.To_String (Console.Columns (I).Title)); Col.Pack_Start (Console.Col_Text, True); Col.Set_Sizing (Gtk.Tree_View_Column.Tree_View_Column_Autosize); Col.Add_Attribute (Console.Col_Text, "text", Glib.Gint (I) - 1); end loop; Console.Tree.Set_Model (+Console.List); Console.Scrolled.Add (Console.Tree); Console.Scrolled.Show_All; end End_Title; -- Start a new row in a report. overriding procedure Start_Row (Console : in out Console_Type) is begin Console.List.Append (Console.Current_Row); end Start_Row; -- Finish a new row in a report. overriding procedure End_Row (Console : in out Console_Type) is begin null; end End_Row; end MAT.Consoles.Gtkmat;
Add a Justify parameter to the Print_Field procedure
Add a Justify parameter to the Print_Field procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
238699b60576007cf062b4863c2384a29b4efa6d
awa/src/awa-events.adb
awa/src/awa-events.adb
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; package body AWA.Events is -- ------------------------------ -- Set the event type which identifies the event. -- ------------------------------ procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index) is begin Event.Kind := Kind; end Set_Event_Kind; -- ------------------------------ -- Get the event type which identifies the event. -- ------------------------------ function Get_Event_Kind (Event : in Module_Event) return Event_Index is begin return Event.Kind; end Get_Event_Kind; -- ------------------------------ -- Set a parameter on the message. -- ------------------------------ procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String) is begin Event.Props.Include (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Get the parameter with the given name. -- ------------------------------ function Get_Parameter (Event : in Module_Event; Name : in String) return String is Pos : constant Util.Beans.Objects.Maps.Cursor := Event.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then return Util.Beans.Objects.To_String (Util.Beans.Objects.Maps.Element (Pos)); else return ""; end if; end Get_Parameter; -- ------------------------------ -- Set the parameters of the message. -- ------------------------------ procedure Set_Parameters (Event : in out Module_Event; Parameters : in Util.Beans.Objects.Maps.Map) is begin Event.Props := Parameters; end Set_Parameters; -- ------------------------------ -- Get the value that corresponds to the parameter with the given name. -- ------------------------------ function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object is begin if Event.Props.Contains (Name) then return Event.Props.Element (Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the entity identifier associated with the event. -- ------------------------------ function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier is begin return Event.Entity; end Get_Entity_Identifier; -- ------------------------------ -- Set the entity identifier associated with the event. -- ------------------------------ procedure Set_Entity_Identifier (Event : in out Module_Event; Id : in ADO.Identifier) is begin Event.Entity := Id; end Set_Entity_Identifier; -- ------------------------------ -- Set the database entity associated with the event. -- ------------------------------ procedure Set_Entity (Event : in out Module_Event; Entity : in ADO.Objects.Object_Ref'Class; Session : in ADO.Sessions.Session'Class) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; begin Event.Entity := ADO.Objects.Get_Value (Key); Event.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Key); end Set_Entity; -- ------------------------------ -- Copy the event properties to the map passed in <tt>Into</tt>. -- ------------------------------ procedure Copy (Event : in Module_Event; Into : in out Util.Beans.Objects.Maps.Map) is begin Into := Event.Props; end Copy; -- ------------------------------ -- Make and return a copy of the event. -- ------------------------------ function Copy (Event : in Module_Event) return Module_Event_Access is Result : constant Module_Event_Access := new Module_Event; begin Result.Kind := Event.Kind; Result.Props := Event.Props; return Result; end Copy; end AWA.Events;
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; package body AWA.Events is -- ------------------------------ -- Set the event type which identifies the event. -- ------------------------------ procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index) is begin Event.Kind := Kind; end Set_Event_Kind; -- ------------------------------ -- Get the event type which identifies the event. -- ------------------------------ function Get_Event_Kind (Event : in Module_Event) return Event_Index is begin return Event.Kind; end Get_Event_Kind; -- ------------------------------ -- Set a parameter on the message. -- ------------------------------ procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String) is begin Event.Props.Include (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in Util.Beans.Objects.Object) is begin Event.Props.Include (Name, Value); end Set_Parameter; -- ------------------------------ -- Get the parameter with the given name. -- ------------------------------ function Get_Parameter (Event : in Module_Event; Name : in String) return String is Pos : constant Util.Beans.Objects.Maps.Cursor := Event.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then return Util.Beans.Objects.To_String (Util.Beans.Objects.Maps.Element (Pos)); else return ""; end if; end Get_Parameter; -- ------------------------------ -- Set the parameters of the message. -- ------------------------------ procedure Set_Parameters (Event : in out Module_Event; Parameters : in Util.Beans.Objects.Maps.Map) is begin Event.Props := Parameters; end Set_Parameters; -- ------------------------------ -- Get the value that corresponds to the parameter with the given name. -- ------------------------------ function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object is begin if Event.Props.Contains (Name) then return Event.Props.Element (Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the entity identifier associated with the event. -- ------------------------------ function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier is begin return Event.Entity; end Get_Entity_Identifier; -- ------------------------------ -- Set the entity identifier associated with the event. -- ------------------------------ procedure Set_Entity_Identifier (Event : in out Module_Event; Id : in ADO.Identifier) is begin Event.Entity := Id; end Set_Entity_Identifier; -- ------------------------------ -- Set the database entity associated with the event. -- ------------------------------ procedure Set_Entity (Event : in out Module_Event; Entity : in ADO.Objects.Object_Ref'Class; Session : in ADO.Sessions.Session'Class) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; begin Event.Entity := ADO.Objects.Get_Value (Key); Event.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Key); end Set_Entity; -- ------------------------------ -- Copy the event properties to the map passed in <tt>Into</tt>. -- ------------------------------ procedure Copy (Event : in Module_Event; Into : in out Util.Beans.Objects.Maps.Map) is begin Into := Event.Props; end Copy; -- ------------------------------ -- Make and return a copy of the event. -- ------------------------------ function Copy (Event : in Module_Event) return Module_Event_Access is Result : constant Module_Event_Access := new Module_Event; begin Result.Kind := Event.Kind; Result.Props := Event.Props; return Result; end Copy; end AWA.Events;
Implement Set_Parameter procedure with Object as value type
Implement Set_Parameter procedure with Object as value type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
53f8d8fb59eb54a1bf16c769d0b868a3f720a9a8
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "76"; copyright_years : constant String := "2015-2021"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; spkg_nls : constant String := "nls"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-8.0"; default_lua : constant String := "5.3"; default_perl : constant String := "5.32"; default_pgsql : constant String := "12"; default_php : constant String := "7.4"; default_python3 : constant String := "3.8"; default_ruby : constant String := "2.7"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_binutils : constant String := "ravensys-binutils:standard"; binutils_version : constant String := "2.37"; obsolete_binutils : constant String := "binutils:ravensys"; -- Remove line upon next update previous_binutils : constant String := "2.35.1"; default_compiler : constant String := "ravensys-gcc"; compiler_version : constant String := "11.2.0"; default_comppath : constant String := default_compiler; previous_default : constant String := "gcc9"; previous_compiler : constant String := "9.3.0"; previous_comppath : constant String := previous_default; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; task_stack_limit : constant := 10_000_000; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "77"; copyright_years : constant String := "2015-2021"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; spkg_nls : constant String := "nls"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-8.0"; default_lua : constant String := "5.3"; default_perl : constant String := "5.32"; default_pgsql : constant String := "12"; default_php : constant String := "7.4"; default_python3 : constant String := "3.8"; default_ruby : constant String := "2.7"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_binutils : constant String := "ravensys-binutils:standard"; binutils_version : constant String := "2.37"; obsolete_binutils : constant String := "binutils:ravensys"; -- Remove line upon next update previous_binutils : constant String := "2.35.1"; default_compiler : constant String := "ravensys-gcc"; compiler_version : constant String := "11.2.0"; default_comppath : constant String := default_compiler; previous_default : constant String := "gcc9"; previous_compiler : constant String := "9.3.0"; previous_comppath : constant String := previous_default; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; task_stack_limit : constant := 10_000_000; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Bump version
Bump version
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
52e842949d5813c6b7bacaa5977c1b6c7a4fd0dc
mat/src/mat-readers.ads
mat/src/mat-readers.ads
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with System; with Util.Properties; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out Message) is abstract; -- Dispatch the message -- procedure Bind (For_Servant : in out Reader_Base) is abstract; -- Bind the servant with the object adapter to register the -- events it recognizes. This is called once we have all the -- information about the structures of events that we can -- receive. ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is tagged limited private; type Manager is access all Manager_Base'Class; -- Register the reader 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_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; 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; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_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 => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is tagged limited record Readers : Reader_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; end record; -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message); -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with System; with Util.Properties; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access all Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out Message) is abstract; -- Dispatch the message -- procedure Bind (For_Servant : in out Reader_Base) is abstract; -- Bind the servant with the object adapter to register the -- events it recognizes. This is called once we have all the -- information about the structures of events that we can -- receive. ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is tagged limited private; type Manager is access all Manager_Base'Class; -- Register the reader 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_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message); private type Endian_Type is (BIG_ENDIAN, LITTLE_ENDIAN); type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; Endian : Endian_Type := LITTLE_ENDIAN; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; 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; use type MAT.Types.Uint16; package Reader_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Message_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 => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is tagged limited record Readers : Reader_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; end record; -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message); -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message); end MAT.Readers;
Add the Frame info in the Dispatch operation
Add the Frame info in the Dispatch operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e382cfd4e9f8702190b343456b22edee7d768f58
regtests/util-serialize-io-csv-tests.adb
regtests/util-serialize-io-csv-tests.adb
----------------------------------------------------------------------- -- serialize-io-csv-tests -- Unit tests for CSV parser -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Serialize.Mappers.Tests; package body Util.Serialize.IO.CSV.Tests is package Caller is new Util.Test_Caller (Test, "Serialize.IO.CSV"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Parse (parse Ok)", Test_Parser'Access); end Add_Tests; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is use Util.Serialize.Mappers.Tests; procedure Check_Parse (Content : in String; Expect : in Integer); Mapping : aliased Util.Serialize.Mappers.Tests.Map_Test_Mapper.Mapper; Mapper : aliased Util.Serialize.Mappers.Tests.Map_Test_Vector_Mapper.Mapper; procedure Check_Parse (Content : in String; Expect : in Integer) is P : Parser; Value : aliased Map_Test_Vector.Vector; begin P.Add_Mapping ("", Mapper'Unchecked_Access); Map_Test_Vector_Mapper.Set_Context (P, Value'Unchecked_Access); P.Parse_String (Content); T.Assert (not P.Has_Error, "Parse error for: " & Content); Util.Tests.Assert_Equals (T, 1, Integer (Value.Length), "Invalid result length"); Util.Tests.Assert_Equals (T, Expect, Integer (Value.Element (1).Value), "Invalid value"); end Check_Parse; HDR : constant String := "name,status,value,bool" & ASCII.CR & ASCII.LF; begin Mapping.Add_Mapping ("name", FIELD_NAME); Mapping.Add_Mapping ("value", FIELD_VALUE); Mapping.Add_Mapping ("status", FIELD_BOOL); Mapping.Add_Mapping ("bool", FIELD_BOOL); Mapper.Set_Mapping (Mapping'Unchecked_Access); Check_Parse (HDR & "joe,false,23,true", 23); Check_Parse (HDR & "billy,false,""12"",true", 12); Check_Parse (HDR & """John Potter"",false,""1234"",true", 1234); Check_Parse (HDR & """John" & ASCII.CR & "Potter"",False,""3234"",True", 3234); Check_Parse (HDR & """John" & ASCII.LF & "Potter"",False,""3234"",True", 3234); end Test_Parser; end Util.Serialize.IO.CSV.Tests;
----------------------------------------------------------------------- -- serialize-io-csv-tests -- Unit tests for CSV parser -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Serialize.Mappers.Tests; with Util.Serialize.IO.JSON.Tests; package body Util.Serialize.IO.CSV.Tests is package Caller is new Util.Test_Caller (Test, "Serialize.IO.CSV"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Parse (parse Ok)", Test_Parser'Access); Caller.Add_Test (Suite, "Test Util.Serialize.IO.CSV.Write", Test_Output'Access); end Add_Tests; -- ------------------------------ -- Check various (basic) JSON valid strings (no mapper). -- ------------------------------ procedure Test_Parser (T : in out Test) is use Util.Serialize.Mappers.Tests; procedure Check_Parse (Content : in String; Expect : in Integer); Mapping : aliased Util.Serialize.Mappers.Tests.Map_Test_Mapper.Mapper; Mapper : aliased Util.Serialize.Mappers.Tests.Map_Test_Vector_Mapper.Mapper; procedure Check_Parse (Content : in String; Expect : in Integer) is P : Parser; Value : aliased Map_Test_Vector.Vector; begin P.Add_Mapping ("", Mapper'Unchecked_Access); Map_Test_Vector_Mapper.Set_Context (P, Value'Unchecked_Access); P.Parse_String (Content); T.Assert (not P.Has_Error, "Parse error for: " & Content); Util.Tests.Assert_Equals (T, 1, Integer (Value.Length), "Invalid result length"); Util.Tests.Assert_Equals (T, Expect, Integer (Value.Element (1).Value), "Invalid value"); end Check_Parse; HDR : constant String := "name,status,value,bool" & ASCII.CR & ASCII.LF; begin Mapping.Add_Mapping ("name", FIELD_NAME); Mapping.Add_Mapping ("value", FIELD_VALUE); Mapping.Add_Mapping ("status", FIELD_BOOL); Mapping.Add_Mapping ("bool", FIELD_BOOL); Mapper.Set_Mapping (Mapping'Unchecked_Access); Check_Parse (HDR & "joe,false,23,true", 23); Check_Parse (HDR & "billy,false,""12"",true", 12); Check_Parse (HDR & """John Potter"",false,""1234"",true", 1234); Check_Parse (HDR & """John" & ASCII.CR & "Potter"",False,""3234"",True", 3234); Check_Parse (HDR & """John" & ASCII.LF & "Potter"",False,""3234"",True", 3234); end Test_Parser; -- ------------------------------ -- Test the CSV output stream generation. -- ------------------------------ procedure Test_Output (T : in out Test) is File : aliased Util.Streams.Files.File_Stream; Stream : Util.Serialize.IO.CSV.Output_Stream; Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.csv"); Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.csv"); begin File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000); Util.Serialize.IO.JSON.Tests.Write_Stream (Stream); Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "CSV output serialization"); end Test_Output; end Util.Serialize.IO.CSV.Tests;
Implement and register the Test_Output procedure
Implement and register the Test_Output procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d86257529b71a6e9124e5d64036298b350d50457
regtests/wiki-tests.adb
regtests/wiki-tests.adb
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 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.Text_IO; with Ada.Directories; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Filters.Autolink; with Wiki.Filters.Variables; with Wiki.Plugins.Templates; with Wiki.Plugins.Conditions; with Wiki.Plugins.Variables; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Documents; with Wiki.Parsers; package body Wiki.Tests is use Ada.Strings.Unbounded; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is use Ada.Directories; Result_File : constant String := To_String (T.Result); Dir : constant String := Containing_Directory (Result_File); Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter; Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Var_Filter : aliased Wiki.Filters.Variables.Variable_Filter; Auto_Filter : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; Variables : aliased Wiki.Plugins.Variables.Variable_Plugin; List_Vars : aliased Wiki.Plugins.Variables.List_Variable_Plugin; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream; type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record; -- Find a plugin knowing its name. overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access; overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is pragma Unreferenced (Factory); begin if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then return Condition'Unchecked_Access; elsif Name = "set" then return Variables'Unchecked_Access; elsif Name = "list" then return List_Vars'Unchecked_Access; else return Template.Find (Name); end if; end Find; Local_Factory : aliased Test_Factory; begin if not Exists (Dir) then Create_Path (Dir); end if; Input.Open (Path => To_String (T.File), Form => "WCEM=8"); Output.Create (Result_File, "WCEM=8"); Template.Set_Template_Path (Containing_Directory (To_String (T.File))); Condition.Append ("public", ""); Condition.Append ("user", "admin"); declare Time : Util.Measures.Stamp; begin Engine.Set_Syntax (T.Source); Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access); Engine.Add_Filter (Toc_Filter'Unchecked_Access); Engine.Add_Filter (Auto_Filter'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Add_Filter (Var_Filter'Unchecked_Access); Engine.Parse (Input'Unchecked_Access, Doc); Util.Measures.Report (Time, "Parse " & To_String (T.Name)); if T.Source = Wiki.SYNTAX_HTML then declare Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name)); end; elsif T.Is_Html then declare Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render HTML " & To_String (T.Name)); end; else declare Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Text " & To_String (T.Name)); end; end if; end; Input.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; procedure Add_Import_Tests; procedure Add_Wiki_Tests; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Wiki_Syntax; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; 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; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Wiki_Syntax; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Wiki_Syntax; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.SYNTAX_MEDIA_WIKI; elsif Ext = "markdown" then Format := Wiki.SYNTAX_MARKDOWN; else Format := Wiki.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Wiki_Syntax'Range loop case Syntax is when Wiki.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Tests;
----------------------------------------------------------------------- -- Render Tests - Unit tests for AWA Wiki rendering -- Copyright (C) 2013, 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.Text_IO; with Ada.Directories; with Util.Measures; with Wiki.Render.Wiki; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Filters.Autolink; with Wiki.Filters.Variables; with Wiki.Plugins.Templates; with Wiki.Plugins.Conditions; with Wiki.Plugins.Variables; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; with Wiki.Documents; with Wiki.Parsers; package body Wiki.Tests is use Ada.Strings.Unbounded; -- ------------------------------ -- Test rendering a wiki text in HTML or text. -- ------------------------------ procedure Test_Render (T : in out Test) is use Ada.Directories; Result_File : constant String := To_String (T.Result); Dir : constant String := Containing_Directory (Result_File); Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; Toc_Filter : aliased Wiki.Filters.TOC.TOC_Filter; Html_Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Var_Filter : aliased Wiki.Filters.Variables.Variable_Filter; Auto_Filter : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; Variables : aliased Wiki.Plugins.Variables.Variable_Plugin; List_Vars : aliased Wiki.Plugins.Variables.List_Variable_Plugin; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Output : aliased Wiki.Streams.Html.Text_IO.Html_File_Output_Stream; type Test_Factory is new Wiki.Plugins.Plugin_Factory with null record; -- Find a plugin knowing its name. overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access; overriding function Find (Factory : in Test_Factory; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access is pragma Unreferenced (Factory); begin if Name = "if" or Name = "else" or Name = "elsif" or Name = "end" then return Condition'Unchecked_Access; elsif Name = "set" then return Variables'Unchecked_Access; elsif Name = "list" then return List_Vars'Unchecked_Access; else return Template.Find (Name); end if; end Find; Local_Factory : aliased Test_Factory; begin if not Exists (Dir) then Create_Path (Dir); end if; Input.Open (Path => To_String (T.File), Form => "WCEM=8"); Output.Create (Result_File, "WCEM=8"); Template.Set_Template_Path (Containing_Directory (To_String (T.File))); Condition.Append ("public", ""); Condition.Append ("user", "admin"); declare Time : Util.Measures.Stamp; begin Engine.Set_Syntax (T.Source); Engine.Set_Plugin_Factory (Local_Factory'Unchecked_Access); Engine.Add_Filter (Toc_Filter'Unchecked_Access); Engine.Add_Filter (Auto_Filter'Unchecked_Access); Engine.Add_Filter (Html_Filter'Unchecked_Access); Engine.Add_Filter (Var_Filter'Unchecked_Access); Engine.Parse (Input'Unchecked_Access, Doc); Util.Measures.Report (Time, "Parse " & To_String (T.Name)); if T.Source = Wiki.SYNTAX_HTML then declare Renderer : aliased Wiki.Render.Wiki.Wiki_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access, T.Format); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Wiki " & To_String (T.Name)); end; elsif T.Is_Html then declare Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render HTML " & To_String (T.Name)); end; else declare Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); Output.Close; Util.Measures.Report (Time, "Render Text " & To_String (T.Name)); end; end if; end; Input.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => To_String (T.Expect), Test => Result_File, Message => "Render"); end Test_Render; -- ------------------------------ -- Test case name -- ------------------------------ overriding function Name (T : in Test) return Util.Tests.Message_String is begin if T.Source = Wiki.SYNTAX_HTML then return Util.Tests.Format ("Test IMPORT " & To_String (T.Name)); elsif T.Is_Html then return Util.Tests.Format ("Test HTML " & To_String (T.Name)); else return Util.Tests.Format ("Test TEXT " & To_String (T.Name)); end if; end Name; -- ------------------------------ -- Perform the test. -- ------------------------------ overriding procedure Run_Test (T : in out Test) is begin T.Test_Render; end Run_Test; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is use Ada.Directories; procedure Add_Import_Tests; procedure Add_Wiki_Tests; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Wiki_Syntax; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access; Result_Dir : constant String := "regtests/result"; Expect_Dir : constant String := "regtests/expect"; 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; function Create_Test (Name : in String; Path : in String; Format : in Wiki.Wiki_Syntax; Prefix : in String; Is_Html : in Boolean) return Test_Case_Access is Tst : Test_Case_Access; begin Tst := new Test; Tst.Is_Html := Is_Html; Tst.Name := To_Unbounded_String (Name); Tst.File := To_Unbounded_String (Path); Tst.Expect := To_Unbounded_String (Expect_Path & Prefix & Name); Tst.Result := To_Unbounded_String (Result_Path & Prefix & Name); Tst.Format := Format; Tst.Source := Format; return Tst; end Create_Test; procedure Add_Wiki_Tests is Dir : constant String := "regtests/files/wiki"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Ext : constant String := Ada.Directories.Extension (Simple); Tst : Test_Case_Access; Format : Wiki.Wiki_Syntax; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then if Ext = "wiki" then Format := Wiki.SYNTAX_GOOGLE; elsif Ext = "dotclear" then Format := Wiki.SYNTAX_DOTCLEAR; elsif Ext = "creole" then Format := Wiki.SYNTAX_CREOLE; elsif Ext = "phpbb" then Format := Wiki.SYNTAX_PHPBB; elsif Ext = "mediawiki" then Format := Wiki.SYNTAX_MEDIA_WIKI; elsif Ext = "markdown" then Format := Wiki.SYNTAX_MARKDOWN; else Format := Wiki.SYNTAX_MIX; end if; Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-html/", True); Suite.Add_Test (Tst.all'Access); Tst := Create_Test (Simple, Path & "/" & Simple, Format, "/wiki-txt/", False); Suite.Add_Test (Tst.all'Access); end if; end; end loop; end Add_Wiki_Tests; procedure Add_Import_Tests is Dir : constant String := "regtests/files/html"; Path : constant String := Util.Tests.Get_Path (Dir); begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Simple : constant String := Simple_Name (Ent); Name : constant String := Base_Name (Simple); Tst : Test_Case_Access; begin if Simple /= "." and then Simple /= ".." and then Simple /= ".svn" and then Simple (Simple'Last) /= '~' then for Syntax in Wiki.Wiki_Syntax'Range loop case Syntax is when Wiki.SYNTAX_CREOLE => Tst := Create_Test (Name & ".creole", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_DOTCLEAR => Tst := Create_Test (Name & ".dotclear", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_MEDIA_WIKI => Tst := Create_Test (Name & ".mediawiki", Path & "/" & Simple, Syntax, "/wiki-import/", True); when Wiki.SYNTAX_MARKDOWN => Tst := Create_Test (Name & ".markdown", Path & "/" & Simple, Syntax, "/wiki-import/", True); when others => Tst := null; end case; if Tst /= null then Tst.Source := Wiki.SYNTAX_HTML; Suite.Add_Test (Tst.all'Access); end if; end loop; end if; end; end loop; end Add_Import_Tests; begin Add_Wiki_Tests; Add_Import_Tests; end Add_Tests; end Wiki.Tests;
Update the test to import HTML into Markdown and verify the result
Update the test to import HTML into Markdown and verify the result
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
182788602188f4bce1efce0b82a64a22b66be2ad
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply, "Blog post page is invalid" ); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/create-blog.html", "create-blog-get.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after getting blog creation page"); ASF.Tests.Assert_Matches (T, "<dl id=.title.*<dt><label for=.title.*" & "<dd><input type=.text.*", Reply, "Blog post admin page is missing input field"); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("post-format", "FORMAT_DOTCLEAR"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "FORMAT_DOTCLEAR"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-format", "FORMAT_DOTCLEAR"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Publish_Date; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017, 2018, 2019, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with Security.Contexts; with ASF.Tests; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Storages.Modules; with AWA.Storages.Beans; with AWA.Storages.Models; with AWA.Storages.Services; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; use type AWA.Storages.Services.Storage_Service_Access; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Servlets.Load", Test_Image_Blog'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply, "Blog post page is invalid" ); end Verify_Anonymous; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous (""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/create-blog.html", "create-blog-get.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after getting blog creation page"); ASF.Tests.Assert_Matches (T, "<dl id=.title.*<dt><label for=.title.*" & "<dd><input type=.text.*", Reply, "Blog post admin page is missing input field"); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("post-format", "FORMAT_DOTCLEAR"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("post-format", "FORMAT_DOTCLEAR"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-format", "FORMAT_DOTCLEAR"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Publish_Date; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; -- ------------------------------ -- Test getting an image from the blog servlet. -- ------------------------------ procedure Test_Image_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Post_Id : constant String := To_String (T.Post_Ident); Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Folder_Bean; Store : AWA.Storages.Models.Storage_Ref; Mgr : AWA.Storages.Services.Storage_Service_Access; Outcome : Ada.Strings.Unbounded.Unbounded_String; Path : constant String := Util.Tests.Get_Path ("regtests/files/images/Ada-Lovelace.jpg"); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Mgr := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (Mgr /= null, "Null storage manager"); -- Make a storage folder. Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Set_Name ("Images"); Folder.Save (Outcome); Store.Set_Folder (Folder); Store.Set_Mime_Type ("image/jpg"); Store.Set_Name ("Ada-Lovelace.jpg"); Mgr.Save (Store, Path, AWA.Storages.Models.FILE); -- First test to make sure we get a 404 error. ASF.Tests.Do_Get (Request, Reply, "/blogs/images/" & Post_Id & "/0/default/Ada-Lovelace.jpg", "Ada-Lovelace.jpg"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_NOT_FOUND, "Invalid response after image get"); -- Second test to get the image. declare Image_Ident : constant String := Util.Strings.Image (Natural (Store.Get_Id)); begin ASF.Tests.Do_Get (Request, Reply, "/blogs/images/" & Post_Id & "/" & Image_Ident & "/default/Ada-Lovelace.jpg", "Ada-Lovelace.jpg"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK, "Invalid response after image get"); end; end Test_Image_Blog; end AWA.Blogs.Tests;
Implement Test_Image_Blog to check that the blog image server is correct
Implement Test_Image_Blog to check that the blog image server is correct
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
95be7c3737b22b8f447dfed41202288270d31d37
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
awa/plugins/awa-blogs/regtests/awa-blogs-tests.ads
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package AWA.Blogs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test creation of blog by simulating web requests. procedure Test_Create_Blog (T : in out Test); end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Blogs.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with record Blog_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Ident : Ada.Strings.Unbounded.Unbounded_String; Post_Uri : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the blog as anonymous users. procedure Verify_Anonymous (T : in out Test; Post : in String); -- Test access to the blog as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of blog by simulating web requests. procedure Test_Create_Blog (T : in out Test); -- Test updating a post by simulating web requests. procedure Test_Update_Post (T : in out Test); end AWA.Blogs.Tests;
Declare two new unit tests Test_Update_Post and Test_Anonymous_Access
Declare two new unit tests Test_Update_Post and Test_Anonymous_Access
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d38ca076bec67749f0ec9cdee1cf0716edab8941
src/security-controllers.ads
src/security-controllers.ads
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- <ul> -- <li>Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- <li>Write a function to allocate instances of the given <b>Controller</b> type -- <li>Register the function under a unique name by using <b>Register_Controller</b> -- </ul> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared accross possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- <ul> -- <li>Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- <li>Write a function to allocate instances of the given <b>Controller</b> type -- <li>Register the function under a unique name by using <b>Register_Controller</b> -- </ul> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
Fix typo in comment
Fix typo in comment
Ada
apache-2.0
Letractively/ada-security
b02dad30fc9fed9397ab453ce179d68b4bfb5336
src/util-beans.ads
src/util-beans.ads
----------------------------------------------------------------------- -- util-beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = Ada Beans = -- -- @include util-beans-objects.ads -- @include util-beans-objects-datasets.ads -- @include util-beans-basic.ads package Util.Beans is pragma Preelaborate; end Util.Beans;
----------------------------------------------------------------------- -- util-beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = Ada Beans = -- A [Java Bean](http://en.wikipedia.org/wiki/JavaBean) is an object that -- allows to access its properties through getters and setters. Java Beans -- rely on the use of Java introspection to discover the Java Bean object properties. -- -- An Ada Bean has some similarities with the Java Bean as it tries to expose -- an object through a set of common interfaces. Since Ada does not have introspection, -- some developer work is necessary. The Ada Bean framework consists of: -- -- * An `Object` concrete type that allows to hold any data type such -- as boolean, integer, floats, strings, dates and Ada bean objects. -- * A `Bean` interface that exposes a `Get_Value` and `Set_Value` -- operation through which the object properties can be obtained and modified. -- * A `Method_Bean` interface that exposes a set of method bindings -- that gives access to the methods provided by the Ada Bean object. -- -- The benefit of Ada beans comes when you need to get a value or invoke -- a method on an object but you don't know at compile time the object or method. -- That step being done later through some external configuration or presentation file. -- -- The Ada Bean framework is the basis for the implementation of -- [Ada Server Faces](http://code.google.com/p/ada-asf/) and -- [Ada EL](http://code.google.com/p/ada-el/). It allows the presentation layer to -- access information provided by Ada beans. -- -- @include util-beans-objects.ads -- @include util-beans-objects-datasets.ads -- @include util-beans-basic.ads package Util.Beans is pragma Preelaborate; end Util.Beans;
Integrate some documentation about Ada beans
Integrate some documentation about Ada beans
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9d9a7ac0322c82a56675e0a87a8ea5215e554425
src/win32/win32.ads
src/win32/win32.ads
------------------------------------------------------------------------------- -- Copyright 2012 Julian Schutsch -- -- This file is part of ParallelSim -- -- ParallelSim is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- ParallelSim is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with ParallelSim. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- -- Revision History -- 18.Mar 2012 Julian Schutsch -- - Original version pragma Ada_2005; with Interfaces; with Interfaces.C; with Interfaces.C.Strings; with System; with Ada.Unchecked_Conversion; package Win32 is type UINT_Type is new Interfaces.Unsigned_32; type DWORD_Type is new Interfaces.Unsigned_32; type HANDLE_Type is new System.Address; type HANDLE_Access is access HANDLE_Type; type UINT_PTR_Type is new Interfaces.C.ptrdiff_t; subtype LONG_PTR_Type is System.Address; type LONG_Type is new Interfaces.C.ptrdiff_t; subtype ULONG_PTR_Type is System.Address; subtype HWND_Type is HANDLE_Type; type WPARAM_Type is new Interfaces.C.ptrdiff_t; subtype LPARAM_Type is LONG_PTR_Type; subtype HINSTANCE_Type is HANDLE_Type; subtype HICON_Type is HANDLE_Type; subtype HCURSOR_Type is HICON_Type; subtype HBRUSH_Type is HANDLE_Type; subtype LPCTSTR_Type is Interfaces.C.Strings.chars_ptr; type WORD_Type is new Interfaces.Unsigned_16; type ATOM_Type is new WORD_Type; subtype HMENU_Type is HANDLE_TYPE; type LRESULT_Type is new LONG_Type; subtype HDC_Type is HANDLE_Type; type BOOL_Type is new Interfaces.C.int; type BYTE_Type is new Interfaces.Unsigned_8; subtype HGLRC_Type is HANDLE_Type; function HANDLEToInteger is new Ada.Unchecked_Conversion (Source => HANDLE_Type, Target => Interfaces.C.ptrdiff_t); NULLHANDLE : constant HANDLE_Type:=HANDLE_Type(System.Null_Address); TRUE : constant BOOL_Type:=1; FALSE : constant BOOL_Type:=0; function MAKEINTRESOURCE (wInteger : WORD_Type) return LPCTSTR_Type; function GET_X_LPARAM (lParam : LPARAM_Type) return Integer; function GET_Y_LPARAM (lParam : LPARAM_Type) return Integer; function LOWORD (lParam : LPARAM_Type) return WORD_Type; function HIWORD (lParam : LPARAM_Type) return WORD_Type; CS_HREDRAW : constant UINT_Type:=2; CS_VREDRAW : constant UINT_Type:=1; CS_OWNDC : constant UINT_Type:=32; WS_OVERLAPPEDWINDOW : constant DWORD_Type:=16#cf0000#; WS_CLIPCHILDREN : constant DWORD_Type:=16#2000000#; WS_CLIPSIBLINGS : constant DWORD_Type:=16#4000000#; WS_EX_APPWINDOW : constant DWORD_Type:=16#40000#; WS_EX_CLIENTEDGE : constant DWORD_Type:=512; WM_MOUSELEAVE : constant := 16#2A3#; WM_PAINT : constant := 15; WM_CREATE : constant := 1; WM_SIZE : constant := 5; WM_SIZING : constant := 532; WM_LBUTTONDBLCLK : constant := 515; WM_RBUTTONDBLCLK : constant := 518; WM_LBUTTONDOWN : constant := 513; WM_LBUTTONUP : constant := 514; WM_RBUTTONDOWN : constant := 516; WM_RBUTTONUP : constant := 517; WM_MOUSEMOVE : constant := 512; WM_DESTROY : constant := 2; WM_ERASEBKGND : constant := 20; WM_KEYDOWN : constant := 256; WM_KEYUP : constant := 257; WM_CHAR : constant := 258; WM_TIMER : constant := 275; WM_QUIT : constant := 18; SW_SHOW : constant := 5; PM_NOREMOVE : constant := 0; PM_REMOVE : constant := 1; PM_NOYIELD : constant := 2; PFD_DRAW_TO_WINDOW : constant:=4; PFD_SUPPORT_OPENGL : constant:=16#20#; PFD_TYPE_RGBA : constant:=0; PFD_MAIN_PLANE : constant:=0; IDI_WINLOGO : constant:=32517; IDI_ASTERISK : constant:=32516; IDI_APPLICATION : constant:=32512; IDI_ERROR : constant:=32513; IDI_EXCLAMATION : constant:=32515; IDC_ARROW : constant:=32512; SW_SHOWNOACTIVATE : constant:=8; STILL_ACTIVE : constant DWORD_Type:=259; type WNDPROC_Access is access function (hWnd : HWND_Type; message : UINT_Type; wParam : WPARAM_Type; lParam : LPARAM_Type) return LRESULT_Type; pragma Convention(C,WNDPROC_Access); type WNDCLASS_Type is record style : UINT_Type := 0; lpfnWndProc : WNDPROC_Access := null; cbClsExtra : Interfaces.C.int := 0; cbWndExtra : Interfaces.C.int := 0; hInstance : HINSTANCE_Type := Win32.NULLHANDLE; hIcon : HICON_Type := Win32.NULLHANDLE; hCursor : HCURSOR_Type := Win32.NULLHANDLE; hbrBackground : HBRUSH_Type := Win32.NULLHANDLE; lpszMenuName : LPCTSTR_Type := Interfaces.C.Strings.Null_Ptr; lpszClassName : LPCTSTR_Type := Interfaces.C.Strings.Null_Ptr; end record; pragma Convention(C,WNDCLASS_Type); type CREATESTRUCT_Type is record lpCreateParams : System.Address:=System.Null_Address; hInstance : HINSTANCE_Type:=Win32.NULLHANDLE; hMenu : HMENU_Type:=Win32.NULLHANDLE; hwndParent : HWND_Type:=Win32.NULLHANDLE; cy : Interfaces.C.int:=0; cx : Interfaces.C.int:=0; y : Interfaces.C.int:=0; x : Interfaces.C.int:=0; style : LONG_Type:=0; lpszName : LPCTSTR_Type:=Interfaces.C.Strings.Null_Ptr; lpszClass : LPCTSTR_Type:=Interfaces.C.Strings.Null_Ptr; dwExStyle : DWORD_Type:=0; end record; type CREATESTRUCT_Access is access CREATESTRUCT_Type; pragma Convention(C,CREATESTRUCT_Type); type POINT_Type is record x : LONG_Type; y : LONG_Type; end record; type MSG_Type is record hwnd : HWND_Type; message : UINT_Type; wParam : UINT_Type; lParam : UINT_Type; time : DWORD_Type; pt : POINT_Type; end record; pragma Convention(C,MSG_Type); HANDLE_FLAG_INHERIT : constant DWORD_Type:=1; HANDLE_FLAG_PROTECT_FROM_CLOSE : constant DWORD_Type:=2; type COMMTIMEOUTS_Type is record ReadIntervalTimeout : DWORD_Type:=DWORD_Type'Last; ReadTotalTimeoutMultiplier : DWORD_Type:=0; ReadTotalTimeoutConstant : DWORD_Type:=0; WriteTotalTimeoutMultiplier : DWORD_Type:=0; WriteTotalTimeoutConstant : DWORD_Type:=0; end record; pragma Convention(C,COMMTIMEOUTS_Type); type SECURITY_ATTRIBUTES_Type is record nLength : DWORD_Type; lpSecurityDescriptor : System.Address:=System.Null_Address; bInheritHandle : BOOL_Type; end record; pragma Convention(C,SECURITY_ATTRIBUTES_Type); type SECURITY_ATTRIBUTES_Access is access SECURITY_ATTRIBUTES_Type; type OVERLAPPED_Type is record Internal : ULONG_PTR_Type := System.Null_Address; InternalHigh : ULONG_PTR_Type := System.Null_Address; Pointer : System.Address := System.Null_Address; hEvent : HANDLE_Type := NULLHANDLE; end record; pragma Convention(C,OVERLAPPED_Type); type PIXELFORMATDESCRIPTOR_Type is record nSize : WORD_Type := 0; nVersion : WORD_Type := 0; dwFlags : DWORD_Type := 0; iPixelType : BYTE_Type := 0; cColorBits : BYTE_Type := 0; cRedBits : BYTE_Type := 0; cRedShift : BYTE_Type := 0; cGreenBits : BYTE_Type := 0; cGreenShift : BYTE_Type := 0; cBlueBits : BYTE_Type := 0; cBlueShift : BYTE_Type := 0; cAlphaBits : BYTE_Type := 0; cAlphaShift : BYTE_Type := 0; cAccumBits : BYTE_Type := 0; cAccumRedBits : BYTE_Type := 0; cAccumGreenBits : BYTE_Type := 0; cAccumBlueBits : BYTE_Type := 0; cAccumAlphaBits : BYTE_Type := 0; cDepthBits : BYTE_Type := 0; cStencilBits : BYTE_Type := 0; cAuxBuffers : BYTE_Type := 0; iLayerType : BYTE_Type := 0; bReserved : BYTE_Type := 0; dwLayerMask : DWORD_Type := 0; dwVisibleMask : DWORD_Type := 0; dwDamageMask : DWORD_Type := 0; end record; pragma Convention(C,PIXELFORMATDESCRIPTOR_Type); type STARTUPINFO_Type is record cb : Interfaces.Unsigned_32; lpReserved : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; lpDesktop : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; lpTitle : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; dwX : Interfaces.Unsigned_32 := 0; dwY : Interfaces.Unsigned_32 := 0; dwXSize : Interfaces.Unsigned_32 := 0; dwYSize : Interfaces.Unsigned_32 := 0; dwXCountChars : Interfaces.Unsigned_32 := 0; dwYCountChars : Interfaces.Unsigned_32 := 0; dwFillAttribute : Interfaces.Unsigned_32 := 0; dwFlags : Interfaces.Unsigned_32 := 0; wShowWindow : Interfaces.Unsigned_16 := 0; cbReserved2 : Interfaces.Unsigned_16 := 0; hStdInput : HANDLE_Type := NULLHANDLE; hStdOutput : HANDLE_Type := NULLHANDLE; hStderr : HANDLE_Type := NULLHANDLE; end record; pragma Convention(C,STARTUPINFO_Type); type PROCESS_INFORMATION_Type is record hProcess : HANDLE_Type := NULLHANDLE; hThread : HANDLE_Type := NULLHANDLE; dwProcessID : Interfaces.Unsigned_32 := 0; dwThreadID : Interfaces.Unsigned_32 := 0; end record; pragma Convention(C,PROCESS_INFORMATION_Type); function GetLastError return DWORD_TYPE; pragma Import(StdCall,GetLastError,"GetLastError"); STARTF_USESTDHANDLES : constant:=16#100#; end Win32;
------------------------------------------------------------------------------- -- Copyright 2012 Julian Schutsch -- -- This file is part of ParallelSim -- -- ParallelSim is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- ParallelSim is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with ParallelSim. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- -- Revision History -- 18.Mar 2012 Julian Schutsch -- - Original version pragma Ada_2005; with Interfaces; with Interfaces.C; with Interfaces.C.Strings; with System; with Ada.Unchecked_Conversion; package Win32 is pragma Linker_Options ("-lgdi32"); pragma Linker_Options ("-lopengl32"); pragma Linker_Options ("-lglu32"); type UINT_Type is new Interfaces.Unsigned_32; type DWORD_Type is new Interfaces.Unsigned_32; type HANDLE_Type is new System.Address; type HANDLE_Access is access HANDLE_Type; type UINT_PTR_Type is new Interfaces.C.ptrdiff_t; subtype LONG_PTR_Type is System.Address; type LONG_Type is new Interfaces.C.ptrdiff_t; subtype ULONG_PTR_Type is System.Address; subtype HWND_Type is HANDLE_Type; type WPARAM_Type is new Interfaces.C.ptrdiff_t; subtype LPARAM_Type is LONG_PTR_Type; subtype HINSTANCE_Type is HANDLE_Type; subtype HICON_Type is HANDLE_Type; subtype HCURSOR_Type is HICON_Type; subtype HBRUSH_Type is HANDLE_Type; subtype LPCTSTR_Type is Interfaces.C.Strings.chars_ptr; type WORD_Type is new Interfaces.Unsigned_16; type ATOM_Type is new WORD_Type; subtype HMENU_Type is HANDLE_TYPE; type LRESULT_Type is new LONG_Type; subtype HDC_Type is HANDLE_Type; type BOOL_Type is new Interfaces.C.int; type BYTE_Type is new Interfaces.Unsigned_8; subtype HGLRC_Type is HANDLE_Type; function HANDLEToInteger is new Ada.Unchecked_Conversion (Source => HANDLE_Type, Target => Interfaces.C.ptrdiff_t); NULLHANDLE : constant HANDLE_Type:=HANDLE_Type(System.Null_Address); TRUE : constant BOOL_Type:=1; FALSE : constant BOOL_Type:=0; function MAKEINTRESOURCE (wInteger : WORD_Type) return LPCTSTR_Type; function GET_X_LPARAM (lParam : LPARAM_Type) return Integer; function GET_Y_LPARAM (lParam : LPARAM_Type) return Integer; function LOWORD (lParam : LPARAM_Type) return WORD_Type; function HIWORD (lParam : LPARAM_Type) return WORD_Type; CS_HREDRAW : constant UINT_Type:=2; CS_VREDRAW : constant UINT_Type:=1; CS_OWNDC : constant UINT_Type:=32; WS_OVERLAPPEDWINDOW : constant DWORD_Type:=16#cf0000#; WS_CLIPCHILDREN : constant DWORD_Type:=16#2000000#; WS_CLIPSIBLINGS : constant DWORD_Type:=16#4000000#; WS_EX_APPWINDOW : constant DWORD_Type:=16#40000#; WS_EX_CLIENTEDGE : constant DWORD_Type:=512; WM_MOUSELEAVE : constant := 16#2A3#; WM_PAINT : constant := 15; WM_CREATE : constant := 1; WM_SIZE : constant := 5; WM_SIZING : constant := 532; WM_LBUTTONDBLCLK : constant := 515; WM_RBUTTONDBLCLK : constant := 518; WM_LBUTTONDOWN : constant := 513; WM_LBUTTONUP : constant := 514; WM_RBUTTONDOWN : constant := 516; WM_RBUTTONUP : constant := 517; WM_MOUSEMOVE : constant := 512; WM_DESTROY : constant := 2; WM_ERASEBKGND : constant := 20; WM_KEYDOWN : constant := 256; WM_KEYUP : constant := 257; WM_CHAR : constant := 258; WM_TIMER : constant := 275; WM_QUIT : constant := 18; SW_SHOW : constant := 5; PM_NOREMOVE : constant := 0; PM_REMOVE : constant := 1; PM_NOYIELD : constant := 2; PFD_DRAW_TO_WINDOW : constant:=4; PFD_SUPPORT_OPENGL : constant:=16#20#; PFD_TYPE_RGBA : constant:=0; PFD_MAIN_PLANE : constant:=0; IDI_WINLOGO : constant:=32517; IDI_ASTERISK : constant:=32516; IDI_APPLICATION : constant:=32512; IDI_ERROR : constant:=32513; IDI_EXCLAMATION : constant:=32515; IDC_ARROW : constant:=32512; SW_SHOWNOACTIVATE : constant:=8; STILL_ACTIVE : constant DWORD_Type:=259; type WNDPROC_Access is access function (hWnd : HWND_Type; message : UINT_Type; wParam : WPARAM_Type; lParam : LPARAM_Type) return LRESULT_Type; pragma Convention(C,WNDPROC_Access); type WNDCLASS_Type is record style : UINT_Type := 0; lpfnWndProc : WNDPROC_Access := null; cbClsExtra : Interfaces.C.int := 0; cbWndExtra : Interfaces.C.int := 0; hInstance : HINSTANCE_Type := Win32.NULLHANDLE; hIcon : HICON_Type := Win32.NULLHANDLE; hCursor : HCURSOR_Type := Win32.NULLHANDLE; hbrBackground : HBRUSH_Type := Win32.NULLHANDLE; lpszMenuName : LPCTSTR_Type := Interfaces.C.Strings.Null_Ptr; lpszClassName : LPCTSTR_Type := Interfaces.C.Strings.Null_Ptr; end record; pragma Convention(C,WNDCLASS_Type); type CREATESTRUCT_Type is record lpCreateParams : System.Address:=System.Null_Address; hInstance : HINSTANCE_Type:=Win32.NULLHANDLE; hMenu : HMENU_Type:=Win32.NULLHANDLE; hwndParent : HWND_Type:=Win32.NULLHANDLE; cy : Interfaces.C.int:=0; cx : Interfaces.C.int:=0; y : Interfaces.C.int:=0; x : Interfaces.C.int:=0; style : LONG_Type:=0; lpszName : LPCTSTR_Type:=Interfaces.C.Strings.Null_Ptr; lpszClass : LPCTSTR_Type:=Interfaces.C.Strings.Null_Ptr; dwExStyle : DWORD_Type:=0; end record; type CREATESTRUCT_Access is access CREATESTRUCT_Type; pragma Convention(C,CREATESTRUCT_Type); type POINT_Type is record x : LONG_Type; y : LONG_Type; end record; type MSG_Type is record hwnd : HWND_Type; message : UINT_Type; wParam : UINT_Type; lParam : UINT_Type; time : DWORD_Type; pt : POINT_Type; end record; pragma Convention(C,MSG_Type); HANDLE_FLAG_INHERIT : constant DWORD_Type:=1; HANDLE_FLAG_PROTECT_FROM_CLOSE : constant DWORD_Type:=2; type COMMTIMEOUTS_Type is record ReadIntervalTimeout : DWORD_Type:=DWORD_Type'Last; ReadTotalTimeoutMultiplier : DWORD_Type:=0; ReadTotalTimeoutConstant : DWORD_Type:=0; WriteTotalTimeoutMultiplier : DWORD_Type:=0; WriteTotalTimeoutConstant : DWORD_Type:=0; end record; pragma Convention(C,COMMTIMEOUTS_Type); type SECURITY_ATTRIBUTES_Type is record nLength : DWORD_Type; lpSecurityDescriptor : System.Address:=System.Null_Address; bInheritHandle : BOOL_Type; end record; pragma Convention(C,SECURITY_ATTRIBUTES_Type); type SECURITY_ATTRIBUTES_Access is access SECURITY_ATTRIBUTES_Type; type OVERLAPPED_Type is record Internal : ULONG_PTR_Type := System.Null_Address; InternalHigh : ULONG_PTR_Type := System.Null_Address; Pointer : System.Address := System.Null_Address; hEvent : HANDLE_Type := NULLHANDLE; end record; pragma Convention(C,OVERLAPPED_Type); type PIXELFORMATDESCRIPTOR_Type is record nSize : WORD_Type := 0; nVersion : WORD_Type := 0; dwFlags : DWORD_Type := 0; iPixelType : BYTE_Type := 0; cColorBits : BYTE_Type := 0; cRedBits : BYTE_Type := 0; cRedShift : BYTE_Type := 0; cGreenBits : BYTE_Type := 0; cGreenShift : BYTE_Type := 0; cBlueBits : BYTE_Type := 0; cBlueShift : BYTE_Type := 0; cAlphaBits : BYTE_Type := 0; cAlphaShift : BYTE_Type := 0; cAccumBits : BYTE_Type := 0; cAccumRedBits : BYTE_Type := 0; cAccumGreenBits : BYTE_Type := 0; cAccumBlueBits : BYTE_Type := 0; cAccumAlphaBits : BYTE_Type := 0; cDepthBits : BYTE_Type := 0; cStencilBits : BYTE_Type := 0; cAuxBuffers : BYTE_Type := 0; iLayerType : BYTE_Type := 0; bReserved : BYTE_Type := 0; dwLayerMask : DWORD_Type := 0; dwVisibleMask : DWORD_Type := 0; dwDamageMask : DWORD_Type := 0; end record; pragma Convention(C,PIXELFORMATDESCRIPTOR_Type); type STARTUPINFO_Type is record cb : Interfaces.Unsigned_32; lpReserved : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; lpDesktop : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; lpTitle : Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.Null_Ptr; dwX : Interfaces.Unsigned_32 := 0; dwY : Interfaces.Unsigned_32 := 0; dwXSize : Interfaces.Unsigned_32 := 0; dwYSize : Interfaces.Unsigned_32 := 0; dwXCountChars : Interfaces.Unsigned_32 := 0; dwYCountChars : Interfaces.Unsigned_32 := 0; dwFillAttribute : Interfaces.Unsigned_32 := 0; dwFlags : Interfaces.Unsigned_32 := 0; wShowWindow : Interfaces.Unsigned_16 := 0; cbReserved2 : Interfaces.Unsigned_16 := 0; hStdInput : HANDLE_Type := NULLHANDLE; hStdOutput : HANDLE_Type := NULLHANDLE; hStderr : HANDLE_Type := NULLHANDLE; end record; pragma Convention(C,STARTUPINFO_Type); type PROCESS_INFORMATION_Type is record hProcess : HANDLE_Type := NULLHANDLE; hThread : HANDLE_Type := NULLHANDLE; dwProcessID : Interfaces.Unsigned_32 := 0; dwThreadID : Interfaces.Unsigned_32 := 0; end record; pragma Convention(C,PROCESS_INFORMATION_Type); function GetLastError return DWORD_TYPE; pragma Import(StdCall,GetLastError,"GetLastError"); STARTF_USESTDHANDLES : constant:=16#100#; end Win32;
add linker_options pragmas for opengl/win
add linker_options pragmas for opengl/win adding them to package library in the project file doesnt seem to work.
Ada
isc
darkestkhan/lumen,darkestkhan/lumen2
17a6db8e7ba7148852a41edb4bc1c03ba8f3fa35
jack-client.adb
jack-client.adb
with C_String.Arrays; with C_String; with Interfaces.C; with System.Address_To_Access_Conversions; package body Jack.Client is package C renames Interfaces.C; use type C.int; use type Port_Name_t; use type System.Address; use type Thin.Port_Flags_t; use type Thin.Status_t; -- -- Activate -- procedure Activate (Client : in Client_t; Failed : out Boolean) is C_Return : constant C.int := Thin.Activate (System.Address (Client)); begin Failed := C_Return /= 0; end Activate; -- -- Close -- procedure Close (Client : in Client_t; Failed : out Boolean) is begin Failed := Thin.Client_Close (System.Address (Client)) /= 0; end Close; -- -- Compare -- function Compare (Left : in Client_t; Right : in Client_t) return Boolean is begin return System.Address (Left) = System.Address (Right); end Compare; function Compare (Left : in Port_t; Right : in Port_t) return Boolean is begin return System.Address (Left) = System.Address (Right); end Compare; -- -- Connect -- procedure Connect (Client : in Client_t; Source_Port : in Port_Name_t; Destination_Port : in Port_Name_t; Failed : out Boolean) is C_Source : aliased C.char_array := C.To_C (Port_Names.To_String (Source_Port)); C_Dest : aliased C.char_array := C.To_C (Port_Names.To_String (Destination_Port)); C_Result : constant C.int := Thin.Connect (Client => System.Address (Client), Source_Port => C_String.To_C_String (C_Source'Unchecked_Access), Destination_Port => C_String.To_C_String (C_Dest'Unchecked_Access)); begin Failed := C_Result /= 0; end Connect; -- -- Disconnect -- procedure Disconnect (Client : in Client_t; Source_Port : in Port_Name_t; Destination_Port : in Port_Name_t; Failed : out Boolean) is C_Source : aliased C.char_array := C.To_C (Port_Names.To_String (Source_Port)); C_Dest : aliased C.char_array := C.To_C (Port_Names.To_String (Destination_Port)); C_Result : constant C.int := Thin.Disconnect (Client => System.Address (Client), Source_Port => C_String.To_C_String (C_Source'Unchecked_Access), Destination_Port => C_String.To_C_String (C_Dest'Unchecked_Access)); begin Failed := C_Result /= 0; end Disconnect; -- -- Get_Ports -- procedure Get_Ports_Free (Data : System.Address); pragma Import (C, Get_Ports_Free, "jack_ada_client_get_ports_free"); procedure Get_Ports (Client : in Client_t; Port_Name_Pattern : in String := ""; Port_Type_Pattern : in String := ""; Port_Flags : in Port_Flags_t := (others => False); Ports : out Port_Name_Set_t) is Name : Port_Name_t; Size : Natural; C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags); C_Name : aliased C.char_array := C.To_C (Port_Name_Pattern); C_Type : aliased C.char_array := C.To_C (Port_Type_Pattern); Ptr_Name : C_String.String_Ptr_t; Ptr_Type : C_String.String_Ptr_t; Address : C_String.Arrays.Pointer_Array_t; begin if Port_Name_Pattern /= Port_Names.Null_Bounded_String then Ptr_Name := C_String.To_C_String (C_Name'Unchecked_Access); end if; if Port_Type_Pattern /= "" then Ptr_Type := C_String.To_C_String (C_Type'Unchecked_Access); end if; Address := Thin.Get_Ports (Client => System.Address (Client), Port_Name_Pattern => Ptr_Name, Type_Name_Pattern => Ptr_Type, Flags => C_Flags); Size := C_String.Arrays.Size_Terminated (Address); for Index in 0 .. Size loop Port_Names.Set_Bounded_String (Source => C_String.Arrays.Index_Terminated (Address, Index), Target => Name); Port_Name_Sets.Insert (Ports, Name); end loop; -- The strings returned by jack_get_ports are heap allocated. Get_Ports_Free (System.Address (Address)); end Get_Ports; -- -- Status, option and flag mapping. -- type Status_Map_t is array (Status_Selector_t) of Thin.Status_t; Status_Map : constant Status_Map_t := Status_Map_t' (Failure => Thin.JackFailure, Invalid_Option => Thin.JackInvalidOption, Name_Not_Unique => Thin.JackNameNotUnique, Server_Started => Thin.JackServerStarted, Server_Failed => Thin.JackServerFailed, Server_Error => Thin.JackServerError, No_Such_Client => Thin.JackNoSuchClient, Load_Failure => Thin.JackLoadFailure, Init_Failure => Thin.JackInitFailure, Shared_Memory_Failure => Thin.JackShmFailure, Version_Error => Thin.JackVersionError); type Options_Map_t is array (Option_Selector_t) of Thin.Options_t; Options_Map : constant Options_Map_t := Options_Map_t' (Do_Not_Start_Server => Thin.JackNoStartServer, Use_Exact_Name => Thin.JackUseExactName, Server_Name => Thin.JackServerName, Load_Name => Thin.JackLoadName, Load_Initialize => Thin.JackLoadInit); type Port_Flags_Map_t is array (Port_Flag_Selector_t) of Thin.Port_Flags_t; Port_Flags_Map : constant Port_Flags_Map_t := Port_Flags_Map_t' (Port_Is_Input => Thin.JackPortIsInput, Port_Is_Output => Thin.JackPortIsOutput, Port_Is_Physical => Thin.JackPortIsPhysical, Port_Can_Monitor => Thin.JackPortCanMonitor, Port_Is_Terminal => Thin.JackPortIsTerminal); function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t is Return_Options : Thin.Options_t := 0; begin for Selector in Options_t'Range loop if Options (Selector) then Return_Options := Return_Options or Options_Map (Selector); end if; end loop; return Return_Options; end Map_Options_To_Thin; function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t is Return_Port_Flags : Thin.Port_Flags_t := 0; begin for Selector in Port_Flags_t'Range loop if Port_Flags (Selector) then Return_Port_Flags := Return_Port_Flags or Port_Flags_Map (Selector); end if; end loop; return Return_Port_Flags; end Map_Port_Flags_To_Thin; function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t is Return_Status : Thin.Status_t := 0; begin for Selector in Status_t'Range loop if Status (Selector) then Return_Status := Return_Status or Status_Map (Selector); end if; end loop; return Return_Status; end Map_Status_To_Thin; function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t is Return_Options : Options_t := (others => False); begin for Selector in Options_t'Range loop Return_Options (Selector) := (Options and Options_Map (Selector)) = Options_Map (Selector); end loop; return Return_Options; end Map_Thin_To_Options; function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t is Return_Port_Flags : Port_Flags_t := (others => False); begin for Selector in Port_Flags_t'Range loop Return_Port_Flags (Selector) := (Port_Flags and Port_Flags_Map (Selector)) = Port_Flags_Map (Selector); end loop; return Return_Port_Flags; end Map_Thin_To_Port_Flags; function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t is Return_Status : Status_t := (others => False); begin for Selector in Status_t'Range loop Return_Status (Selector) := (Status and Status_Map (Selector)) = Status_Map (Selector); end loop; return Return_Status; end Map_Thin_To_Status; -- -- Open -- procedure Open (Client_Name : in String; Options : in Options_t; Client : out Client_t; Status : in out Status_t) is function C_Client_Open (Client_Name : C_String.String_Not_Null_Ptr_t; Options : Thin.Options_t; Status : System.Address) return System.Address; pragma Import (C, C_Client_Open, "jack_ada_client_open"); C_Client : System.Address; C_Name : aliased C.char_array := C.To_C (Client_Name); C_Options : constant Thin.Options_t := Map_Options_To_Thin (Options); C_Status : aliased Thin.Status_t := 0; begin pragma Assert (Client_Name /= ""); C_Client := C_Client_Open (Client_Name => C_String.To_C_String (C_Name'Unchecked_Access), Options => C_Options, Status => C_Status'Address); Status := Map_Thin_To_Status (C_Status); if C_Client = System.Null_Address then Client := Invalid_Client; else Client := Client_t (C_Client); end if; end Open; -- -- Port_Register -- procedure Port_Register (Client : in Client_t; Port : out Port_t; Port_Name : in Port_Name_t; Port_Type : in String := Default_Audio_Type; Port_Flags : in Port_Flags_t := (others => False); Buffer_Size : in Natural := 0) is C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags); C_Name : aliased C.char_array := C.To_C (Port_Names.To_String (Port_Name)); C_Port : System.Address; C_Type : aliased C.char_array := C.To_C (Port_Type); begin C_Port := Thin.Port_Register (Client => System.Address (Client), Port_Name => C_String.To_C_String (C_Name'Unchecked_Access), Port_Type => C_String.To_C_String (C_Type'Unchecked_Access), Flags => C_Flags, Buffer_Size => C.unsigned_long (Buffer_Size)); if C_Port = System.Null_Address then Port := Invalid_Port; else Port := Port_t (C_Port); end if; end Port_Register; -- -- Generic_Callbacks -- package body Generic_Callbacks is package Convert_Process is new System.Address_To_Access_Conversions (Process_Callback_State_t); function C_Set_Process_Callback (Client : System.Address; Callback : access procedure (Number_Of_Frames : Thin.Number_Of_Frames_t; Data : System.Address); Data : System.Address) return Thin.Integer_t; pragma Import (C, C_Set_Process_Callback, "jack_set_process_callback"); procedure Process_Callback_Inner (Number_Of_Frames : Thin.Number_Of_Frames_t; Data : System.Address) is State : Process_Callback_State_t; for State'Address use Data; pragma Import (Ada, State); begin State.Callback (Number_Of_Frames => Number_Of_Frames_t (Number_Of_Frames), User_Data => State.User_Data); end Process_Callback_Inner; procedure Set_Process_Callback (Client : in Client_t; State : in Process_Callback_State_Access_t; Failed : out Boolean) is Pointer : constant Convert_Process.Object_Pointer := Convert_Process.Object_Pointer (State); begin Failed := 0 /= C_Set_Process_Callback (Client => System.Address (Client), Callback => Process_Callback_Inner'Access, Data => Convert_Process.To_Address (Pointer)); end Set_Process_Callback; end Generic_Callbacks; -- -- To_Address -- function To_Address (Client : in Client_t) return System.Address is begin return System.Address (Client); end To_Address; function To_Address (Port : in Port_t) return System.Address is begin return System.Address (Port); end To_Address; end Jack.Client;
with C_String.Arrays; with C_String; with Interfaces.C; with System.Address_To_Access_Conversions; package body Jack.Client is package C renames Interfaces.C; use type C.int; use type Port_Name_t; use type System.Address; use type Thin.Port_Flags_t; use type Thin.Status_t; -- -- Activate -- procedure Activate (Client : in Client_t; Failed : out Boolean) is C_Return : constant C.int := Thin.Activate (System.Address (Client)); begin Failed := C_Return /= 0; end Activate; -- -- Close -- procedure Close (Client : in Client_t; Failed : out Boolean) is begin Failed := Thin.Client_Close (System.Address (Client)) /= 0; end Close; -- -- Compare -- function Compare (Left : in Client_t; Right : in Client_t) return Boolean is begin return System.Address (Left) = System.Address (Right); end Compare; function Compare (Left : in Port_t; Right : in Port_t) return Boolean is begin return System.Address (Left) = System.Address (Right); end Compare; -- -- Connect -- procedure Connect (Client : in Client_t; Source_Port : in Port_Name_t; Destination_Port : in Port_Name_t; Failed : out Boolean) is C_Source : aliased C.char_array := C.To_C (Port_Names.To_String (Source_Port)); C_Dest : aliased C.char_array := C.To_C (Port_Names.To_String (Destination_Port)); C_Result : constant C.int := Thin.Connect (Client => System.Address (Client), Source_Port => C_String.To_C_String (C_Source'Unchecked_Access), Destination_Port => C_String.To_C_String (C_Dest'Unchecked_Access)); begin Failed := C_Result /= 0; end Connect; -- -- Disconnect -- procedure Disconnect (Client : in Client_t; Source_Port : in Port_Name_t; Destination_Port : in Port_Name_t; Failed : out Boolean) is C_Source : aliased C.char_array := C.To_C (Port_Names.To_String (Source_Port)); C_Dest : aliased C.char_array := C.To_C (Port_Names.To_String (Destination_Port)); C_Result : constant C.int := Thin.Disconnect (Client => System.Address (Client), Source_Port => C_String.To_C_String (C_Source'Unchecked_Access), Destination_Port => C_String.To_C_String (C_Dest'Unchecked_Access)); begin Failed := C_Result /= 0; end Disconnect; -- -- Get_Ports -- procedure Get_Ports_Free (Data : System.Address); pragma Import (C, Get_Ports_Free, "jack_ada_client_get_ports_free"); procedure Get_Ports (Client : in Client_t; Port_Name_Pattern : in String := ""; Port_Type_Pattern : in String := ""; Port_Flags : in Port_Flags_t := (others => False); Ports : out Port_Name_Set_t) is Name : Port_Name_t; Size : Natural; C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags); C_Name : aliased C.char_array := C.To_C (Port_Name_Pattern); C_Type : aliased C.char_array := C.To_C (Port_Type_Pattern); Ptr_Name : C_String.String_Ptr_t; Ptr_Type : C_String.String_Ptr_t; Address : C_String.Arrays.Pointer_Array_t; begin if Port_Name_Pattern /= Port_Names.Null_Bounded_String then Ptr_Name := C_String.To_C_String (C_Name'Unchecked_Access); end if; if Port_Type_Pattern /= "" then Ptr_Type := C_String.To_C_String (C_Type'Unchecked_Access); end if; Address := Thin.Get_Ports (Client => System.Address (Client), Port_Name_Pattern => Ptr_Name, Type_Name_Pattern => Ptr_Type, Flags => C_Flags); if Address /= System.Null_Address then Size := C_String.Arrays.Size_Terminated (Address); if Size > 0 then for Index in 0 .. Size - 1 loop Port_Names.Set_Bounded_String (Source => C_String.Arrays.Index_Terminated (Address, Index), Target => Name); Port_Name_Sets.Insert (Ports, Name); end loop; end if; -- The strings returned by jack_get_ports are heap allocated. Get_Ports_Free (System.Address (Address)); end if; end Get_Ports; -- -- Status, option and flag mapping. -- type Status_Map_t is array (Status_Selector_t) of Thin.Status_t; Status_Map : constant Status_Map_t := Status_Map_t' (Failure => Thin.JackFailure, Invalid_Option => Thin.JackInvalidOption, Name_Not_Unique => Thin.JackNameNotUnique, Server_Started => Thin.JackServerStarted, Server_Failed => Thin.JackServerFailed, Server_Error => Thin.JackServerError, No_Such_Client => Thin.JackNoSuchClient, Load_Failure => Thin.JackLoadFailure, Init_Failure => Thin.JackInitFailure, Shared_Memory_Failure => Thin.JackShmFailure, Version_Error => Thin.JackVersionError); type Options_Map_t is array (Option_Selector_t) of Thin.Options_t; Options_Map : constant Options_Map_t := Options_Map_t' (Do_Not_Start_Server => Thin.JackNoStartServer, Use_Exact_Name => Thin.JackUseExactName, Server_Name => Thin.JackServerName, Load_Name => Thin.JackLoadName, Load_Initialize => Thin.JackLoadInit); type Port_Flags_Map_t is array (Port_Flag_Selector_t) of Thin.Port_Flags_t; Port_Flags_Map : constant Port_Flags_Map_t := Port_Flags_Map_t' (Port_Is_Input => Thin.JackPortIsInput, Port_Is_Output => Thin.JackPortIsOutput, Port_Is_Physical => Thin.JackPortIsPhysical, Port_Can_Monitor => Thin.JackPortCanMonitor, Port_Is_Terminal => Thin.JackPortIsTerminal); function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t is Return_Options : Thin.Options_t := 0; begin for Selector in Options_t'Range loop if Options (Selector) then Return_Options := Return_Options or Options_Map (Selector); end if; end loop; return Return_Options; end Map_Options_To_Thin; function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t is Return_Port_Flags : Thin.Port_Flags_t := 0; begin for Selector in Port_Flags_t'Range loop if Port_Flags (Selector) then Return_Port_Flags := Return_Port_Flags or Port_Flags_Map (Selector); end if; end loop; return Return_Port_Flags; end Map_Port_Flags_To_Thin; function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t is Return_Status : Thin.Status_t := 0; begin for Selector in Status_t'Range loop if Status (Selector) then Return_Status := Return_Status or Status_Map (Selector); end if; end loop; return Return_Status; end Map_Status_To_Thin; function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t is Return_Options : Options_t := (others => False); begin for Selector in Options_t'Range loop Return_Options (Selector) := (Options and Options_Map (Selector)) = Options_Map (Selector); end loop; return Return_Options; end Map_Thin_To_Options; function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t is Return_Port_Flags : Port_Flags_t := (others => False); begin for Selector in Port_Flags_t'Range loop Return_Port_Flags (Selector) := (Port_Flags and Port_Flags_Map (Selector)) = Port_Flags_Map (Selector); end loop; return Return_Port_Flags; end Map_Thin_To_Port_Flags; function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t is Return_Status : Status_t := (others => False); begin for Selector in Status_t'Range loop Return_Status (Selector) := (Status and Status_Map (Selector)) = Status_Map (Selector); end loop; return Return_Status; end Map_Thin_To_Status; -- -- Open -- procedure Open (Client_Name : in String; Options : in Options_t; Client : out Client_t; Status : in out Status_t) is function C_Client_Open (Client_Name : C_String.String_Not_Null_Ptr_t; Options : Thin.Options_t; Status : System.Address) return System.Address; pragma Import (C, C_Client_Open, "jack_ada_client_open"); C_Client : System.Address; C_Name : aliased C.char_array := C.To_C (Client_Name); C_Options : constant Thin.Options_t := Map_Options_To_Thin (Options); C_Status : aliased Thin.Status_t := 0; begin pragma Assert (Client_Name /= ""); C_Client := C_Client_Open (Client_Name => C_String.To_C_String (C_Name'Unchecked_Access), Options => C_Options, Status => C_Status'Address); Status := Map_Thin_To_Status (C_Status); if C_Client = System.Null_Address then Client := Invalid_Client; else Client := Client_t (C_Client); end if; end Open; -- -- Port_Register -- procedure Port_Register (Client : in Client_t; Port : out Port_t; Port_Name : in Port_Name_t; Port_Type : in String := Default_Audio_Type; Port_Flags : in Port_Flags_t := (others => False); Buffer_Size : in Natural := 0) is C_Flags : constant Thin.Port_Flags_t := Map_Port_Flags_To_Thin (Port_Flags); C_Name : aliased C.char_array := C.To_C (Port_Names.To_String (Port_Name)); C_Port : System.Address; C_Type : aliased C.char_array := C.To_C (Port_Type); begin C_Port := Thin.Port_Register (Client => System.Address (Client), Port_Name => C_String.To_C_String (C_Name'Unchecked_Access), Port_Type => C_String.To_C_String (C_Type'Unchecked_Access), Flags => C_Flags, Buffer_Size => C.unsigned_long (Buffer_Size)); if C_Port = System.Null_Address then Port := Invalid_Port; else Port := Port_t (C_Port); end if; end Port_Register; -- -- Generic_Callbacks -- package body Generic_Callbacks is package Convert_Process is new System.Address_To_Access_Conversions (Process_Callback_State_t); function C_Set_Process_Callback (Client : System.Address; Callback : access procedure (Number_Of_Frames : Thin.Number_Of_Frames_t; Data : System.Address); Data : System.Address) return Thin.Integer_t; pragma Import (C, C_Set_Process_Callback, "jack_set_process_callback"); procedure Process_Callback_Inner (Number_Of_Frames : Thin.Number_Of_Frames_t; Data : System.Address) is State : Process_Callback_State_t; for State'Address use Data; pragma Import (Ada, State); begin State.Callback (Number_Of_Frames => Number_Of_Frames_t (Number_Of_Frames), User_Data => State.User_Data); end Process_Callback_Inner; procedure Set_Process_Callback (Client : in Client_t; State : in Process_Callback_State_Access_t; Failed : out Boolean) is Pointer : constant Convert_Process.Object_Pointer := Convert_Process.Object_Pointer (State); begin Failed := 0 /= C_Set_Process_Callback (Client => System.Address (Client), Callback => Process_Callback_Inner'Access, Data => Convert_Process.To_Address (Pointer)); end Set_Process_Callback; end Generic_Callbacks; -- -- To_Address -- function To_Address (Client : in Client_t) return System.Address is begin return System.Address (Client); end To_Address; function To_Address (Port : in Port_t) return System.Address is begin return System.Address (Port); end To_Address; end Jack.Client;
Check NULL return, correct use of Size
Check NULL return, correct use of Size
Ada
isc
io7m/coreland-jack-ada,io7m/coreland-jack-ada
bc36ebe30172a248f6ccb0dc35d3e112c97c00b6
examples/filesystem/src/main.adb
examples/filesystem/src/main.adb
with HAL; use HAL; with Virtual_File_System; use Virtual_File_System; with HAL.Filesystem; use HAL.Filesystem; with Semihosting; with Semihosting.Filesystem; use Semihosting.Filesystem; procedure Main is procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname); procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname) is Status : Status_Kind; DH : Directory_Handle_Ref; begin Status := FS.Open_Directory (Path, DH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Directory '" & Path & "' Error: " & Status'Img); else declare Ent : Directory_Entry; Index : Positive := 1; begin Semihosting.Log_Line ("Listing '" & Path & "' content:"); loop Status := DH.Read_Entry (Index, Ent); if Status = Status_Ok then Semihosting.Log_Line (" - '" & DH.Entry_Name (Index) & "'"); Semihosting.Log_Line (" Kind: " & Ent.Entry_Type'Img); else exit; end if; Index := Index + 1; end loop; end; end if; end List_Dir; My_VFS : VFS; My_VFS2 : aliased VFS; My_VFS3 : aliased VFS; My_SHFS : aliased SHFS; Status : Status_Kind; FH : File_Handle_Ref; Data : Byte_Array (1 .. 10); begin Status := My_VFS.Mount (Path => "test1", Filesystem => My_VFS2'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS2.Mount (Path => "test2", Filesystem => My_VFS3'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS.Mount (Path => "host", Filesystem => My_SHFS'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("//test1/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1//no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1/test2/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Open ("/host/tmp/test.shfs", FH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Error: " & Status'Img); end if; Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Seek (10); if Status /= Status_Ok then Semihosting.Log_Line ("Seek Error: " & Status'Img); end if; Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Close; if Status /= Status_Ok then Semihosting.Log_Line ("Close Error: " & Status'Img); end if; List_Dir (My_VFS, "/"); List_Dir (My_VFS, "/test1"); List_Dir (My_VFS, "/test1/"); end Main;
with HAL; use HAL; with Virtual_File_System; use Virtual_File_System; with HAL.Filesystem; use HAL.Filesystem; with Semihosting; with Semihosting.Filesystem; use Semihosting.Filesystem; with File_Block_Drivers; use File_Block_Drivers; with Partitions; use Partitions; procedure Main is procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname); procedure List_Partitions (FS : in out FS_Driver'Class; Path_To_Disk_Image : Pathname); -------------- -- List_Dir -- -------------- procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname) is Status : Status_Kind; DH : Directory_Handle_Ref; begin Status := FS.Open_Directory (Path, DH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Directory '" & Path & "' Error: " & Status'Img); else declare Ent : Directory_Entry; Index : Positive := 1; begin Semihosting.Log_Line ("Listing '" & Path & "' content:"); loop Status := DH.Read_Entry (Index, Ent); if Status = Status_Ok then Semihosting.Log_Line (" - '" & DH.Entry_Name (Index) & "'"); Semihosting.Log_Line (" Kind: " & Ent.Entry_Type'Img); else exit; end if; Index := Index + 1; end loop; end; end if; end List_Dir; --------------------- -- List_Partitions -- --------------------- procedure List_Partitions (FS : in out FS_Driver'Class; Path_To_Disk_Image : Pathname) is File : File_Handle_Ref; begin if FS.Open (Path_To_Disk_Image, File) /= Status_Ok then Semihosting.Log_Line ("Cannot open disk image '" & Path_To_Disk_Image & "'"); return; end if; declare Disk : aliased File_Block_Driver (File); Nbr : Natural; P_Entry : Partition_Entry; begin Nbr := Number_Of_Partitions (Disk'Unchecked_Access); Semihosting.Log_Line ("Disk '" & Path_To_Disk_Image & "' has " & Nbr'Img & " parition(s)"); for Id in 1 .. Nbr loop if Get_Partition_Entry (Disk'Unchecked_Access, Id, P_Entry) /= Status_Ok then Semihosting.Log_Line ("Cannot read partition :" & Id'Img); else Semihosting.Log_Line (" - partition :" & Id'Img); Semihosting.Log_Line (" Status:" & P_Entry.Status'Img); Semihosting.Log_Line (" Kind: " & P_Entry.Kind'Img); Semihosting.Log_Line (" LBA: " & P_Entry.First_Sector_LBA'Img); Semihosting.Log_Line (" Number of sectors: " & P_Entry.Number_Of_Sectors'Img); end if; end loop; end; end List_Partitions; My_VFS : VFS; My_VFS2 : aliased VFS; My_VFS3 : aliased VFS; My_SHFS : aliased SHFS; Status : Status_Kind; FH : File_Handle_Ref; Data : Byte_Array (1 .. 10); begin Status := My_VFS.Mount (Path => "test1", Filesystem => My_VFS2'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS2.Mount (Path => "test2", Filesystem => My_VFS3'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; Status := My_VFS.Mount (Path => "host", Filesystem => My_SHFS'Unchecked_Access); if Status /= Status_Ok then Semihosting.Log_Line ("Mount Error: " & Status'Img); end if; List_Partitions (My_VFS, "/host/tmp/disk.img"); Status := My_VFS.Unlink ("/test1/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("//test1/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1//no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Unlink ("/test1/test2/no_file"); if Status /= Status_Ok then Semihosting.Log_Line ("Unlink Error: " & Status'Img); end if; Status := My_VFS.Open ("/host/tmp/test.shfs", FH); if Status /= Status_Ok then Semihosting.Log_Line ("Open Error: " & Status'Img); end if; Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Seek (10); if Status /= Status_Ok then Semihosting.Log_Line ("Seek Error: " & Status'Img); end if; Status := FH.Read (Data); if Status /= Status_Ok then Semihosting.Log_Line ("Read Error: " & Status'Img); end if; for C of Data loop Semihosting.Log (Character'Val (Integer (C))); end loop; Semihosting.Log_New_Line; Status := FH.Close; if Status /= Status_Ok then Semihosting.Log_Line ("Close Error: " & Status'Img); end if; List_Dir (My_VFS, "/"); List_Dir (My_VFS, "/test1"); List_Dir (My_VFS, "/test1/"); end Main;
Add disk partition listing
examples/filesystem: Add disk partition listing
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
5a3538c864f35bc5184b009d674572c3c67066a6
src/mysql/ado-mysql.adb
src/mysql/ado-mysql.adb
----------------------------------------------------------------------- -- ado-mysql -- Database Drivers -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Configs; with ADO.Connections.Mysql; package body ADO.Mysql is -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin ADO.Configs.Initialize (Config); ADO.Connections.Mysql.Initialize; end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin ADO.Configs.Initialize (Config); ADO.Connections.Mysql.Initialize; end Initialize; end ADO.Mysql;
----------------------------------------------------------------------- -- ado-mysql -- Database Drivers -- Copyright (C) 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Configs; with ADO.Connections.Mysql; package body ADO.Mysql is -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is begin ADO.Connections.Mysql.Initialize; end Initialize; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin ADO.Configs.Initialize (Config); Initialize; end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin ADO.Configs.Initialize (Config); Initialize; end Initialize; end ADO.Mysql;
Implement the Initialize procedure and use it
Implement the Initialize procedure and use it
Ada
apache-2.0
stcarrez/ada-ado
ae139d3aa3653318e5ad3a1acf5750cbca6d5359
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
Letractively/ada-security