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
0423a6bf9246720196396f4acb3acb752220ffb7
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Components.Core.Views; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; use Util.Locales; use type ASF.Components.Base.UIComponent_Access; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); -- If the view could not be found, do not report any error yet. -- The SC_NOT_FOUND response will be returned when rendering the response. if Facelets.Is_Null (Tree) then return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); -- If there was some error while building the view, return now. -- The SC_NOT_FOUND response will also be returned when rendering the response. if Node = null then return; end if; ASF.Components.Root.Set_Root (View, Node, View_Name); if Context.Get_Locale = NULL_LOCALE then if Node.all in Core.Views.UIView'Class then Context.Set_Locale (Core.Views.UIView'Class (Node.all).Get_Locale (Context)); else Context.Set_Locale (Handler.Calculate_Locale (Context)); end if; end if; end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale is pragma Unreferenced (Handler); App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; begin return App.Calculate_Locale (Context); end Calculate_Locale; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Components.Core.Views; with ASF.Converters; with ASF.Validators; with EL.Objects; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); overriding function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; overriding function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get a converter from a name. -- Returns the converter object or null if there is no converter. -- ------------------------------ function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is begin return Context.Application.Find (Name); end Get_Converter; -- ------------------------------ -- Get a validator from a name. -- Returns the validator object or null if there is no validator. -- ------------------------------ function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is begin return Context.Application.Find_Validator (Name); end Get_Validator; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; use Util.Locales; use type ASF.Components.Base.UIComponent_Access; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); -- If the view could not be found, do not report any error yet. -- The SC_NOT_FOUND response will be returned when rendering the response. if Facelets.Is_Null (Tree) then return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); -- If there was some error while building the view, return now. -- The SC_NOT_FOUND response will also be returned when rendering the response. if Node = null then return; end if; ASF.Components.Root.Set_Root (View, Node, View_Name); if Context.Get_Locale = NULL_LOCALE then if Node.all in Core.Views.UIView'Class then Context.Set_Locale (Core.Views.UIView'Class (Node.all).Get_Locale (Context)); else Context.Set_Locale (Handler.Calculate_Locale (Context)); end if; end if; end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale is pragma Unreferenced (Handler); App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; begin return App.Calculate_Locale (Context); end Calculate_Locale; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
Implement the Get_Converter and Get_Validator operarion on the Facelet_Context type Remove Get_Application
Implement the Get_Converter and Get_Validator operarion on the Facelet_Context type Remove Get_Application
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c5b4d5d6382f61f855baea6a3e1ba89d9d1e485c
src/http/util-http-clients.adb
src/http/util-http-clients.adb
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Http.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients"); -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; 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. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; 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 Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (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 (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; 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 Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a 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 (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; if Http.Manager = null then Log.Error ("No HTTP manager was defined"); raise Program_Error with "No HTTP manager was defined."; end if; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; -- ------------------------------ -- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Put (Request, URL, Data, Reply); end Put; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ procedure Set_Timeout (Request : in out Client; Timeout : in Duration) is begin Request.Manager.Set_Timeout (Request, Timeout); end Set_Timeout; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Http.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients"); -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; 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. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; 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 Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (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 (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; 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 Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a 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 (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; if Http.Manager = null then Log.Error ("No HTTP manager was defined"); raise Program_Error with "No HTTP manager was defined."; end if; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; -- ------------------------------ -- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Put (Request, URL, Data, Reply); end Put; -- ------------------------------ -- Execute a http DELETE request on the given URL. -- ------------------------------ procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Delete (Request, URL, Reply); end Delete; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ procedure Set_Timeout (Request : in out Client; Timeout : in Duration) is begin Request.Manager.Set_Timeout (Request, Timeout); end Set_Timeout; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
Implement the Delete procedure
Implement the Delete procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
004260b4494d518c6ca66b8b24cc0997845125de
src/wiki-parsers.ads
src/wiki-parsers.ads
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; private with Wiki.Buffers; private with Util.Stacks; private with Wiki.Nodes; private with Wiki.Html_Parser; -- == Wiki Parsers {#wiki-parsers} == -- The `Wikis.Parsers` package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki `Document` -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- `Set_Syntax` procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- `Add_Filter` procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki `Document` is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The `Parse` procedure is then used to parse either a string content or some stream -- represented by the `Input_Stream` interface. After the `Parse` procedure -- completes, the `Document` instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; subtype Parser_Type is Parser; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Trim_End is (None, Left, Right, Both); type Block; type Content_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Content_Access; Last : Natural := 0; Content : Wiki.Strings.WString (1 .. Len); end record; procedure Next (Content : in out Content_Access; Pos : in out Positive) with Inline_Always; use Wiki.Strings.Wide_Wide_Builders; type Block_Type is record Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH; Level : Natural := 0; Marker : Wiki.Strings.WChar := ' '; Number : Integer := 0; end record; type Parser_State_Type is (State_Html_Doctype, State_Html_Comment, State_Html_Attribute, State_Html_Element); type Block_Access is access all Block_Type; package Block_Stack is new Util.Stacks (Element_Type => Block_Type, Element_Type_Access => Block_Access); type Parser_Handler is access procedure (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access); type Parser is tagged limited record Context : aliased Wiki.Plugins.Plugin_Context; Previous_Syntax : Wiki_Syntax; Document : Wiki.Documents.Document; Parse_Block : Parser_Handler; Parse_Inline : Parser_Handler; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Line_Buffer : Wiki.Buffers.Builder (512); Text_Buffer : Wiki.Buffers.Builder (512); Empty_Line : Boolean := True; Is_Last_Line : Boolean := False; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; In_Table : Boolean := False; In_Html : Boolean := False; Need_Paragraph : Boolean := True; Pending_Paragraph : Boolean := False; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Preformat_Column : Natural := 1; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Previous_Tag : Html_Tag := UNKNOWN_TAG; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE; Blocks : Block_Stack.Stack; Previous_Line_Empty : Boolean := False; Header_Level : Natural := 0; Is_Empty_Paragraph : Boolean := True; Pre_Tag_Counter : Natural := 0; -- Pre-format code block Preformat_Fence : Wiki.Strings.WChar; Preformat_Indent : Natural := 0; Preformat_Fcount : Natural := 0; Preformat_Format : Wiki.Strings.BString (32); Html : Wiki.Html_Parser.Parser_Type; end record; -- Read the next wiki input line in the line buffer. procedure Read_Line (Parser : in out Parser_Type'Class; Buffer : out Wiki.Buffers.Buffer_Access); function Is_List_Item (P : in Parser; Level : in Natural) return Boolean; function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access; From : in Positive; Token : in Wiki.Strings.WChar) return Boolean; -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser; Trim : in Trim_End := None); procedure Flush_Block (Parser : in out Parser_Type); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); procedure Pop_List (P : in out Parser; Level : in Natural; Marker : in Wiki.Strings.WChar); procedure Pop_List (P : in out Parser); -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Returns true if we are included from another wiki content. function Is_Included (P : in Parser) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; procedure Process_Html (P : in out Parser; Kind : in Wiki.Html_Parser.State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Toggle_Format (P : in out Parser; Format : in Format_Type); -- Parse the beginning or the end of a single character sequence. -- Example: -- _name_ *bold* `code` procedure Parse_Format (P : in out Parser; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Expect : in Wiki.Strings.WChar; Format : in Format_Type); -- Parse the beginning or the end of a double character sequence. -- Example: -- --name-- **bold** ~~strike~~ procedure Parse_Format_Double (P : in out Parser; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Expect : in Wiki.Strings.WChar; Format : in Format_Type); -- Push a new block kind on the block stack. procedure Push_Block (P : in out Parser; Kind : in Wiki.Nodes.Node_Kind; Level : in Integer := 0; Marker : in Wiki.Strings.WChar := ' '; Number : in Integer := 0); -- Pop the current block stack. procedure Pop_Block (P : in out Parser); procedure Pop_All (P : in out Parser); procedure Pop_Block_Until (P : in out Parser; Kind : in Wiki.Nodes.Node_Kind; Level : in Integer); procedure Append_Text (P : in out Parser; Text : in Wiki.Strings.BString; From : in Positive; To : in Positive); NAME_ATTR : aliased constant String := "name"; HREF_ATTR : aliased constant String := "href"; LANG_ATTR : aliased constant String := "lang"; TITLE_ATTR : aliased constant String := "title"; end Wiki.Parsers;
----------------------------------------------------------------------- -- wiki-parsers -- Wiki parser -- Copyright (C) 2011, 2015, 2016, 2018, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Plugins; with Wiki.Filters; with Wiki.Strings; with Wiki.Documents; with Wiki.Streams; private with Wiki.Buffers; private with Util.Stacks; private with Wiki.Nodes; private with Wiki.Html_Parser; -- == Wiki Parsers {#wiki-parsers} == -- The `Wikis.Parsers` package implements a parser for several well known wiki formats -- but also for HTML. While reading the input, the parser populates a wiki `Document` -- instance with headers, paragraphs, links, and other elements. -- -- Engine : Wiki.Parsers.Parser; -- -- Before using the parser, it must be configured to choose the syntax by using the -- `Set_Syntax` procedure: -- -- Engine.Set_Syntax (Wiki.SYNTAX_HTML); -- -- The parser can be configured to use filters. A filter is added by using the -- `Add_Filter` procedure. A filter is added at begining of the chain so that -- the filter added last is called first. The wiki `Document` is always built through -- the filter chain so this allows filters to change or alter the content that was parsed. -- -- Engine.Add_Filter (TOC'Unchecked_Access); -- Engine.Add_Filter (Filter'Unchecked_Access); -- -- The `Parse` procedure is then used to parse either a string content or some stream -- represented by the `Input_Stream` interface. After the `Parse` procedure -- completes, the `Document` instance holds the wiki document. -- -- Engine.Parse (Some_Text, Doc); -- package Wiki.Parsers is pragma Preelaborate; type Parser is tagged limited private; subtype Parser_Type is Parser; -- Set the plugin factory to find and use plugins. procedure Set_Plugin_Factory (Engine : in out Parser; Factory : in Wiki.Plugins.Plugin_Factory_Access); -- Set the wiki syntax that the wiki engine must use. procedure Set_Syntax (Engine : in out Parser; Syntax : in Wiki_Syntax := SYNTAX_MARKDOWN); -- Add a filter in the wiki engine. procedure Add_Filter (Engine : in out Parser; Filter : in Wiki.Filters.Filter_Type_Access); -- Set the plugin context. procedure Set_Context (Engine : in out Parser; Context : in Wiki.Plugins.Plugin_Context); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. The string is assumed to be in UTF-8 format. procedure Parse (Engine : in out Parser; Text : in String; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.WString; Doc : in out Wiki.Documents.Document); -- Parse the wiki text contained in <b>Text</b> according to the wiki syntax -- defined on the parser. procedure Parse (Engine : in out Parser; Text : in Wiki.Strings.UString; Doc : in out Wiki.Documents.Document); -- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured -- on the wiki engine. procedure Parse (Engine : in out Parser; Stream : in Wiki.Streams.Input_Stream_Access; Doc : in out Wiki.Documents.Document); private type Trim_End is (None, Left, Right, Both); type Block; type Content_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Content_Access; Last : Natural := 0; Content : Wiki.Strings.WString (1 .. Len); end record; procedure Next (Content : in out Content_Access; Pos : in out Positive) with Inline_Always; use Wiki.Strings.Wide_Wide_Builders; type Block_Type is record Kind : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_PARAGRAPH; Level : Natural := 0; Marker : Wiki.Strings.WChar := ' '; Number : Integer := 0; end record; type Parser_State_Type is (State_Html_Doctype, State_Html_Comment, State_Html_Attribute, State_Html_Element); type Block_Access is access all Block_Type; package Block_Stack is new Util.Stacks (Element_Type => Block_Type, Element_Type_Access => Block_Access); type Parser_Handler is access procedure (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access); type Parser is tagged limited record Context : aliased Wiki.Plugins.Plugin_Context; Previous_Syntax : Wiki_Syntax; Document : Wiki.Documents.Document; Parse_Block : Parser_Handler; Parse_Inline : Parser_Handler; Format : Wiki.Format_Map; Text : Wiki.Strings.BString (512); Line_Buffer : Wiki.Buffers.Builder (512); Text_Buffer : Wiki.Buffers.Builder (512); Empty_Line : Boolean := True; Is_Last_Line : Boolean := False; Is_Eof : Boolean := False; In_Paragraph : Boolean := False; In_List : Boolean := False; In_Table : Boolean := False; In_Html : Boolean := False; Need_Paragraph : Boolean := True; Pending_Paragraph : Boolean := False; Link_Double_Bracket : Boolean := False; Link_No_Space : Boolean := False; Is_Dotclear : Boolean := False; Link_Title_First : Boolean := False; Check_Image_Link : Boolean := False; Header_Offset : Integer := 0; Preformat_Column : Natural := 1; Quote_Level : Natural := 0; Escape_Char : Wiki.Strings.WChar; Param_Char : Wiki.Strings.WChar; List_Level : Natural := 0; Previous_Tag : Html_Tag := UNKNOWN_TAG; Reader : Wiki.Streams.Input_Stream_Access := null; Attributes : Wiki.Attributes.Attribute_List; Current_Node : Wiki.Nodes.Node_Kind := Wiki.Nodes.N_NONE; Blocks : Block_Stack.Stack; Previous_Line_Empty : Boolean := False; Header_Level : Natural := 0; Is_Empty_Paragraph : Boolean := True; Pre_Tag_Counter : Natural := 0; -- Pre-format code block Preformat_Fence : Wiki.Strings.WChar; Preformat_Indent : Natural := 0; Preformat_Fcount : Natural := 0; Preformat_Format : Wiki.Strings.BString (32); Html : Wiki.Html_Parser.Parser_Type; end record; -- Read the next wiki input line in the line buffer. procedure Read_Line (Parser : in out Parser_Type'Class; Buffer : out Wiki.Buffers.Buffer_Access); function Is_List_Item (P : in Parser; Level : in Natural) return Boolean; function Is_Single_Token (Text : in Wiki.Buffers.Buffer_Access; From : in Positive; Token : in Wiki.Strings.WChar) return Boolean; -- Flush the wiki text that was collected in the text buffer. procedure Flush_Text (P : in out Parser; Trim : in Trim_End := None); procedure Flush_Block (Parser : in out Parser_Type); -- Flush the wiki dl/dt/dd definition list. procedure Flush_List (P : in out Parser); procedure Pop_List (P : in out Parser; Level : in Natural; Marker : in Wiki.Strings.WChar; Number : in Natural); procedure Pop_List (P : in out Parser); function Get_Current_Level (Parser : in Parser_Type) return Natural; -- Check if the link refers to an image and must be rendered as an image. -- Returns a positive index of the start the the image link. function Is_Image (P : in Parser; Link : in Wiki.Strings.WString) return Natural; -- Returns true if we are included from another wiki content. function Is_Included (P : in Parser) return Boolean; -- Find the plugin with the given name. -- Returns null if there is no such plugin. function Find (P : in Parser; Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access; type String_Array is array (Positive range <>) of Wiki.String_Access; procedure Process_Html (P : in out Parser; Kind : in Wiki.Html_Parser.State_Type; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List); procedure Start_Element (P : in out Parser; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List); procedure End_Element (P : in out Parser; Tag : in Wiki.Html_Tag); procedure Toggle_Format (P : in out Parser; Format : in Format_Type); -- Parse the beginning or the end of a single character sequence. -- Example: -- _name_ *bold* `code` procedure Parse_Format (P : in out Parser; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Expect : in Wiki.Strings.WChar; Format : in Format_Type); -- Parse the beginning or the end of a double character sequence. -- Example: -- --name-- **bold** ~~strike~~ procedure Parse_Format_Double (P : in out Parser; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive; Expect : in Wiki.Strings.WChar; Format : in Format_Type); -- Push a new block kind on the block stack. procedure Push_Block (P : in out Parser; Kind : in Wiki.Nodes.Node_Kind; Level : in Integer := 0; Marker : in Wiki.Strings.WChar := ' '; Number : in Integer := 0); -- Pop the current block stack. procedure Pop_Block (P : in out Parser); procedure Pop_All (P : in out Parser); procedure Pop_Block_Until (P : in out Parser; Kind : in Wiki.Nodes.Node_Kind; Level : in Integer); procedure Append_Text (P : in out Parser; Text : in Wiki.Strings.BString; From : in Positive; To : in Positive); NAME_ATTR : aliased constant String := "name"; HREF_ATTR : aliased constant String := "href"; LANG_ATTR : aliased constant String := "lang"; TITLE_ATTR : aliased constant String := "title"; end Wiki.Parsers;
Add get_Current_Level
Add get_Current_Level
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
81e38522428ee1adaa0e32a2ace7e7f4837146a4
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Components.Core.Views; with ASF.Converters; with ASF.Validators; with EL.Objects; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); overriding function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; overriding function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get a converter from a name. -- Returns the converter object or null if there is no converter. -- ------------------------------ function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is begin return Context.Application.Find (Name); end Get_Converter; -- ------------------------------ -- Get a validator from a name. -- Returns the validator object or null if there is no validator. -- ------------------------------ function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is begin return Context.Application.Find_Validator (Name); end Get_Validator; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; use Util.Locales; use type ASF.Components.Base.UIComponent_Access; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); -- If the view could not be found, do not report any error yet. -- The SC_NOT_FOUND response will be returned when rendering the response. if Facelets.Is_Null (Tree) then return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); -- If there was some error while building the view, return now. -- The SC_NOT_FOUND response will also be returned when rendering the response. if Node = null then return; end if; ASF.Components.Root.Set_Root (View, Node, View_Name); if Context.Get_Locale = NULL_LOCALE then if Node.all in Core.Views.UIView'Class then Context.Set_Locale (Core.Views.UIView'Class (Node.all).Get_Locale (Context)); else Context.Set_Locale (Handler.Calculate_Locale (Context)); end if; end if; end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale is pragma Unreferenced (Handler); App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; begin return App.Calculate_Locale (Context); end Calculate_Locale; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Components.Core.Views; with ASF.Converters; with ASF.Validators; with EL.Objects; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); overriding function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; overriding function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get a converter from a name. -- Returns the converter object or null if there is no converter. -- ------------------------------ function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is begin return Context.Application.Find (Name); end Get_Converter; -- ------------------------------ -- Get a validator from a name. -- Returns the validator object or null if there is no validator. -- ------------------------------ function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is begin return Context.Application.Find_Validator (Name); end Get_Validator; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; use Util.Locales; use type ASF.Components.Base.UIComponent_Access; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); -- If the view could not be found, do not report any error yet. -- The SC_NOT_FOUND response will be returned when rendering the response. if Facelets.Is_Null (Tree) then return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); -- If there was some error while building the view, return now. -- The SC_NOT_FOUND response will also be returned when rendering the response. if Node = null then return; end if; ASF.Components.Root.Set_Root (View, Node, View_Name); if Context.Get_Locale = NULL_LOCALE then if Node.all in Core.Views.UIView'Class then Context.Set_Locale (Core.Views.UIView'Class (Node.all).Get_Locale (Context)); else Context.Set_Locale (Handler.Calculate_Locale (Context)); end if; end if; end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale is pragma Unreferenced (Handler); App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; begin return App.Calculate_Locale (Context); end Calculate_Locale; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := Conf.Get (VIEW_DIR_PARAM); Handler.View_Ext := Conf.Get (VIEW_EXT_PARAM); Handler.File_Ext := Conf.Get (VIEW_FILE_EXT_PARAM); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
Fix getting a configuration value as an Unbounded_String result
Fix getting a configuration value as an Unbounded_String result
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
eb2a7c6594a62ef347aabac9b79b715a11e856e7
regtests/util-streams-buffered-tests.adb
regtests/util-streams-buffered-tests.adb
----------------------------------------------------------------------- -- streams.buffered.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Texts; package body Util.Streams.Buffered.Tests is use Util.Tests; use Util.Streams.Texts; package Caller is new Util.Test_Caller (Test, "Streams.Buffered"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Read", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (String)", Test_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (Stream_Array)", Test_Write_Stream'Access); end Add_Tests; -- ------------------------------ -- Write on a buffered stream and read what was written. -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); Stream.Write ("abcd"); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "abcd", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Read_Write; -- ------------------------------ -- Write on a buffer and force regular flush on a larger buffer -- ------------------------------ procedure Test_Write (T : in out Test) is Big_Stream : aliased Output_Buffer_Stream; Stream : Output_Buffer_Stream; Size : Stream_Element_Offset := 0; Count : constant Stream_Element_Offset := 1000; Max_Size : constant Stream_Element_Offset := (Count * (Count + 1)) / 2; begin Big_Stream.Initialize (Size => Natural (Max_Size)); Stream.Initialize (Output => Big_Stream'Unchecked_Access, Size => 13); for I in 1 .. Count loop declare S : Stream_Element_Array (1 .. I); begin for J in S'Range loop S (J) := Stream_Element (J mod 255); end loop; Stream.Write (S); Stream.Flush; Size := Size + I; Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed"); -- Verify that 'Big_Stream' holds the expected number of bytes. Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1, "Target stream has an invalid write position at " & Stream_Element_Offset'Image (I)); end; end loop; end Test_Write; -- ------------------------------ -- Write on a buffer and force regular flush on a larger buffer -- ------------------------------ procedure Test_Write_Stream (T : in out Test) is Big_Stream : aliased Output_Buffer_Stream; Stream : Output_Buffer_Stream; Size : Stream_Element_Offset := 0; Count : constant Stream_Element_Offset := 200; Max_Size : constant Stream_Element_Offset := 5728500; begin Big_Stream.Initialize (Size => Natural (Max_Size)); for Buf_Size in 1 .. 19 loop Stream.Initialize (Output => Big_Stream'Unchecked_Access, Size => Buf_Size); for I in 1 .. Count loop for Repeat in 1 .. 5 loop declare S : Stream_Element_Array (1 .. I); begin for J in S'Range loop S (J) := Stream_Element'Val (J mod 255); end loop; for J in 1 .. Repeat loop Stream.Write (S); end loop; Stream.Flush; Size := Size + (I) * Stream_Element_Offset (Repeat); Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed"); -- Verify that 'Big_Stream' holds the expected number of bytes. Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1, "Target stream has an invalid write position at " & Stream_Element_Offset'Image (I) & " with buffer " & Natural'Image (Buf_Size) & " repeat " & Natural'Image (Repeat)); end; end loop; end loop; end loop; Assert_Equals (T, Integer (Max_Size), Integer (Big_Stream.Get_Size), "Invalid final size"); end Test_Write_Stream; end Util.Streams.Buffered.Tests;
----------------------------------------------------------------------- -- streams.buffered.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Texts; package body Util.Streams.Buffered.Tests is use Util.Tests; use Util.Streams.Texts; package Caller is new Util.Test_Caller (Test, "Streams.Buffered"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Read", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (String)", Test_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Write, Flush (Stream_Array)", Test_Write_Stream'Access); end Add_Tests; -- ------------------------------ -- Write on a buffered stream and read what was written. -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); Stream.Write ("abcd"); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "abcd", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Read_Write; -- ------------------------------ -- Write on a buffer and force regular flush on a larger buffer -- ------------------------------ procedure Test_Write (T : in out Test) is Big_Stream : aliased Output_Buffer_Stream; Stream : Output_Buffer_Stream; Size : Stream_Element_Offset := 0; Count : constant Stream_Element_Offset := 1000; Max_Size : constant Stream_Element_Offset := (Count * (Count + 1)) / 2; begin Big_Stream.Initialize (Size => Natural (Max_Size)); Stream.Initialize (Output => Big_Stream'Access, Size => 13); for I in 1 .. Count loop declare S : Stream_Element_Array (1 .. I); begin for J in S'Range loop S (J) := Stream_Element (J mod 255); end loop; Stream.Write (S); Stream.Flush; Size := Size + I; Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed"); -- Verify that 'Big_Stream' holds the expected number of bytes. Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1, "Target stream has an invalid write position at " & Stream_Element_Offset'Image (I)); end; end loop; end Test_Write; -- ------------------------------ -- Write on a buffer and force regular flush on a larger buffer -- ------------------------------ procedure Test_Write_Stream (T : in out Test) is Big_Stream : aliased Output_Buffer_Stream; Stream : Output_Buffer_Stream; Size : Stream_Element_Offset := 0; Count : constant Stream_Element_Offset := 200; Max_Size : constant Stream_Element_Offset := 5728500; begin Big_Stream.Initialize (Size => Natural (Max_Size)); for Buf_Size in 1 .. 19 loop Stream.Initialize (Output => Big_Stream'Access, Size => Buf_Size); for I in 1 .. Count loop for Repeat in 1 .. 5 loop declare S : Stream_Element_Array (1 .. I); begin for J in S'Range loop S (J) := Stream_Element'Val (J mod 255); end loop; for J in 1 .. Repeat loop Stream.Write (S); end loop; Stream.Flush; Size := Size + (I) * Stream_Element_Offset (Repeat); Assert_Equals (T, 1, Integer (Stream.Write_Pos), "Stream must be flushed"); -- Verify that 'Big_Stream' holds the expected number of bytes. Assert_Equals (T, Integer (Size), Integer (Big_Stream.Write_Pos) - 1, "Target stream has an invalid write position at " & Stream_Element_Offset'Image (I) & " with buffer " & Natural'Image (Buf_Size) & " repeat " & Natural'Image (Repeat)); end; end loop; end loop; end loop; Assert_Equals (T, Integer (Max_Size), Integer (Big_Stream.Get_Size), "Invalid final size"); end Test_Write_Stream; end Util.Streams.Buffered.Tests;
Replace Unchecked_Access by Access in stream initialization
Replace Unchecked_Access by Access in stream initialization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
3dbfd4a1dc33730874eb96ee98568f21748dc395
src/natools-s_expressions-generic_caches.ads
src/natools-s_expressions-generic_caches.ads
------------------------------------------------------------------------------ -- Copyright (c) 2013-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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.S_Expressions.Generic_Caches provides a simple memory container -- -- for S-expressions. The container is append-only, and provides cursors to -- -- replay it from start. -- -- This is a generic package that allow client-selected storage pools. An -- -- instance with default storage pools is provided in -- -- Natools.S_Expressions.Caches. -- -- The intended usage is efficient caching of S-expressions in memory. For -- -- more flexible in-memory S-expression objects, -- -- see Natools.S_Expressions.Holders. -- ------------------------------------------------------------------------------ with System.Storage_Pools; with Natools.S_Expressions.Printers; private with Ada.Finalization; private with Ada.Unchecked_Deallocation; private with Natools.References; generic Atom_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; Counter_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; Structure_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; package Natools.S_Expressions.Generic_Caches is type Reference is new Printers.Printer with private; overriding procedure Open_List (Output : in out Reference); overriding procedure Append_Atom (Output : in out Reference; Data : in Atom); overriding procedure Close_List (Output : in out Reference); function Duplicate (Cache : Reference) return Reference; -- Create a new copy of the S-expression held in Cache and return it type Cursor is new Descriptor with private; overriding function Current_Event (Object : in Cursor) return Events.Event; overriding function Current_Atom (Object : in Cursor) return Atom; overriding function Current_Level (Object : in Cursor) return Natural; overriding procedure Query_Atom (Object : in Cursor; Process : not null access procedure (Data : in Atom)); overriding procedure Read_Atom (Object : in Cursor; Data : out Atom; Length : out Count); overriding procedure Next (Object : in out Cursor; Event : out Events.Event); function First (Cache : Reference'Class) return Cursor; -- Create a new Cursor pointing at the beginning of Cache private type Atom_Access is access Atom; for Atom_Access'Storage_Pool use Atom_Pool; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Atom, Atom_Access); type Node; type Node_Access is access Node; for Node_Access'Storage_Pool use Structure_Pool; type Node_Kind is (Atom_Node, List_Node); type Node (Kind : Node_Kind) is record Parent : Node_Access; Next : Node_Access; case Kind is when Atom_Node => Data : Atom_Access; when List_Node => Child : Node_Access; end case; end record; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Node, Node_Access); type Tree is new Ada.Finalization.Limited_Controlled with record Root : Node_Access := null; Last : Node_Access := null; Opening : Boolean := False; end record; procedure Append (Exp : in out Tree; Kind : in Node_Kind; Data : in Atom_Access := null); -- Append a new node of the given Kind to Exp procedure Close_List (Exp : in out Tree); -- Close innermost list function Create_Tree return Tree; -- Create a new empty Tree function Duplicate (Source : Tree) return Tree; -- Deep copy of a Tree object overriding procedure Finalize (Object : in out Tree); -- Release all nodes contained in Object package Trees is new References (Tree, Structure_Pool, Counter_Pool); type Reference is new Printers.Printer with record Exp : Trees.Reference; end record; type Cursor is new Descriptor with record Exp : Trees.Reference := Trees.Create (Create_Tree'Access); Position : Node_Access := null; Opening : Boolean := False; end record; end Natools.S_Expressions.Generic_Caches;
------------------------------------------------------------------------------ -- Copyright (c) 2013-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. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.S_Expressions.Generic_Caches provides a simple memory container -- -- for S-expressions. The container is append-only, and provides cursors to -- -- replay it from start. -- -- This is a generic package that allow client-selected storage pools. An -- -- instance with default storage pools is provided in -- -- Natools.S_Expressions.Caches. -- -- The intended usage is efficient caching of S-expressions in memory. For -- -- more flexible in-memory S-expression objects, -- -- see Natools.S_Expressions.Holders. -- ------------------------------------------------------------------------------ with System.Storage_Pools; with Natools.S_Expressions.Printers; private with Ada.Finalization; private with Ada.Unchecked_Deallocation; private with Natools.References; generic Atom_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; Counter_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; Structure_Pool : in out System.Storage_Pools.Root_Storage_Pool'Class; package Natools.S_Expressions.Generic_Caches is type Reference is new Printers.Printer with private; overriding procedure Open_List (Output : in out Reference); overriding procedure Append_Atom (Output : in out Reference; Data : in Atom); overriding procedure Close_List (Output : in out Reference); function Duplicate (Cache : Reference) return Reference; -- Create a new copy of the S-expression held in Cache and return it type Cursor is new Descriptor with private; overriding function Current_Event (Object : in Cursor) return Events.Event; overriding function Current_Atom (Object : in Cursor) return Atom; overriding function Current_Level (Object : in Cursor) return Natural; overriding procedure Query_Atom (Object : in Cursor; Process : not null access procedure (Data : in Atom)); overriding procedure Read_Atom (Object : in Cursor; Data : out Atom; Length : out Count); overriding procedure Next (Object : in out Cursor; Event : out Events.Event); function First (Cache : Reference'Class) return Cursor; -- Create a new Cursor pointing at the beginning of Cache private type Atom_Access is access Atom; for Atom_Access'Storage_Pool use Atom_Pool; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Atom, Atom_Access); type Node; type Node_Access is access Node; for Node_Access'Storage_Pool use Structure_Pool; type Node_Kind is (Atom_Node, List_Node); type Node (Kind : Node_Kind) is record Parent : Node_Access; Next : Node_Access; case Kind is when Atom_Node => Data : Atom_Access; when List_Node => Child : Node_Access; end case; end record; procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Node, Node_Access); type Tree is new Ada.Finalization.Limited_Controlled with record Root : Node_Access := null; Last : Node_Access := null; Opening : Boolean := False; end record; procedure Append (Exp : in out Tree; Kind : in Node_Kind; Data : in Atom_Access := null); -- Append a new node of the given Kind to Exp procedure Close_List (Exp : in out Tree); -- Close innermost list function Create_Tree return Tree; -- Create a new empty Tree function Duplicate (Source : Tree) return Tree; -- Deep copy of a Tree object overriding procedure Finalize (Object : in out Tree); -- Release all nodes contained in Object package Trees is new References (Tree, Structure_Pool, Counter_Pool); type Reference is new Printers.Printer with record Exp : Trees.Reference; end record; type Cursor is new Descriptor with record Exp : Trees.Reference := Trees.Null_Reference; Position : Node_Access := null; Opening : Boolean := False; end record; end Natools.S_Expressions.Generic_Caches;
fix exception in empty Cursor assignment (though I don't understand what was wrong)
s_expressions-generic_caches: fix exception in empty Cursor assignment (though I don't understand what was wrong)
Ada
isc
faelys/natools
52cd06043419604239e393cb3ad03002d64a985b
src/util-serialize-mappers.adb
src/util-serialize-mappers.adb
----------------------------------------------------------------------- -- util-serialize-mappers -- Serialize objects in various formats -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; package body Util.Serialize.Mappers is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers", Util.Log.WARN_LEVEL); -- ----------------------- -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. -- ----------------------- procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object) is begin if Handler.Mapper /= null then Handler.Mapper.all.Execute (Map, Ctx, Value); end if; end Execute; function Is_Proxy (Controller : in Mapper) return Boolean is begin return Controller.Is_Proxy_Mapper; end Is_Proxy; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String; Attribute : in Boolean := False) return Mapper_Access is use type Ada.Strings.Unbounded.Unbounded_String; Node : Mapper_Access := Controller.First_Child; begin if Node = null and Controller.Mapper /= null then return Controller.Mapper.Find_Mapper (Name, Attribute); end if; while Node /= null loop if Node.Name = Name then if (Attribute = False and Node.Mapping = null) or else not Node.Mapping.Is_Attribute then return Node; end if; if Attribute and Node.Mapping.Is_Attribute then return Node; end if; end if; Node := Node.Next_Mapping; end loop; return null; end Find_Mapper; -- ----------------------- -- Find a path component representing a child mapper under <b>From</b> and -- identified by the given <b>Name</b>. If the mapper is not found, a new -- Mapper_Node is created. -- ----------------------- procedure Find_Path_Component (From : in out Mapper'Class; Name : in String; Result : out Mapper_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access := From.First_Child; begin if Node = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); From.First_Child := Result; return; end if; loop if Node.Name = Name then Result := Node; return; end if; if Node.Next_Mapping = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); Node.Next_Mapping := Result; return; end if; Node := Node.Next_Mapping; end loop; end Find_Path_Component; -- ----------------------- -- Build the mapping tree that corresponds to the given <b>Path</b>. -- Each path component is represented by a <b>Mapper_Node</b> element. -- The node is created if it does not exists. -- ----------------------- procedure Build_Path (Into : in out Mapper'Class; Path : in String; Last_Pos : out Natural; Node : out Mapper_Access) is Pos : Natural; begin Node := Into'Unchecked_Access; Last_Pos := Path'First; loop Pos := Util.Strings.Index (Source => Path, Char => '/', From => Last_Pos); if Pos = 0 then Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last), Result => Node); Last_Pos := Path'Last + 1; else Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1), Result => Node); Last_Pos := Pos + 1; end if; exit when Last_Pos > Path'Last; end loop; end Build_Path; -- ----------------------- -- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>. -- The <b>Path</b> string describes the matching node using a simplified XPath notation. -- Example: -- info/first_name matches: <info><first_name>...</first_name></info> -- info/a/b/name matches: <info><a><b><name>...</name></b></a></info> -- ----------------------- procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapper_Access) is Node : Mapper_Access; Last_Pos : Natural; procedure Copy (To : in Mapper_Access; From : in Mapper_Access) is N : Mapper_Access; Src : Mapper_Access := From; begin while Src /= null loop N := Src.Clone; N.Is_Clone := True; N.Next_Mapping := To.First_Child; To.First_Child := N; if Src.First_Child /= null then Copy (N, Src.First_Child); end if; Src := Src.Next_Mapping; end loop; end Copy; begin Log.Info ("Mapping {0} for mapper X", Path); -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapper /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; Copy (Node, Map.First_Child); end Add_Mapping; procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapping_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access; Last_Pos : Natural; begin Log.Info ("Mapping {0}", Path); -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapping /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Length (Node.Name) = 0 then Log.Warn ("Mapped name is empty in mapping path {0}", Path); elsif Element (Node.Name, 1) = '@' then Delete (Node.Name, 1, 1); Map.Is_Attribute := True; else Map.Is_Attribute := False; end if; Node.Mapping := Map; Node.Mapper := Into'Unchecked_Access; end Add_Mapping; -- ----------------------- -- Clone the <b>Handler</b> instance and get a copy of that single object. -- ----------------------- function Clone (Handler : in Mapper) return Mapper_Access is Result : constant Mapper_Access := new Mapper; begin Result.Name := Handler.Name; Result.Mapper := Handler.Mapper; Result.Mapping := Handler.Mapping; Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper; Result.Is_Clone := True; return Result; end Clone; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- procedure Set_Member (Handler : in Mapper; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False; Context : in out Util.Serialize.Contexts.Context'Class) is Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute); begin if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then Map.Mapper.all.Execute (Map.Mapping.all, Context, Value); end if; end Set_Member; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Start_Object (Context, Name); end if; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Finish_Object (Context, Name); end if; end Finish_Object; -- ----------------------- -- Dump the mapping tree on the logger using the INFO log level. -- ----------------------- procedure Dump (Handler : in Mapper'Class; Log : in Util.Log.Loggers.Logger'Class; Prefix : in String := "") is procedure Dump (Map : in Mapper'Class); -- ----------------------- -- Dump the mapping description -- ----------------------- procedure Dump (Map : in Mapper'Class) is begin if Map.Mapping /= null and then Map.Mapping.Is_Attribute then Log.Info (" {0}@{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Mapping.Name)); else Log.Info (" {0}/{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Name)); Dump (Map, Log, Prefix & "/" & Ada.Strings.Unbounded.To_String (Map.Name)); end if; end Dump; begin Iterate (Handler, Dump'Access); end Dump; procedure Iterate (Controller : in Mapper; Process : not null access procedure (Map : in Mapper'Class)) is Node : Mapper_Access := Controller.First_Child; begin -- Pass 1: process the attributes first while Node /= null loop if Node.Mapping /= null and then Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; -- Pass 2: process the elements Node := Controller.First_Child; while Node /= null loop if Node.Mapping = null or else not Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; end Iterate; -- ----------------------- -- Finalize the object and release any mapping. -- ----------------------- overriding procedure Finalize (Controller : in out Mapper) is procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access); Node : Mapper_Access := Controller.First_Child; Next : Mapper_Access; begin Controller.First_Child := null; while Node /= null loop Next := Node.Next_Mapping; Free (Node); Node := Next; end loop; if not Controller.Is_Clone then Free (Controller.Mapping); else Controller.Mapping := null; end if; end Finalize; end Util.Serialize.Mappers;
----------------------------------------------------------------------- -- util-serialize-mappers -- Serialize objects in various formats -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; package body Util.Serialize.Mappers is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers", Util.Log.WARN_LEVEL); -- ----------------------- -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. -- ----------------------- procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object) is begin if Handler.Mapper /= null then Handler.Mapper.all.Execute (Map, Ctx, Value); end if; end Execute; function Is_Proxy (Controller : in Mapper) return Boolean is begin return Controller.Is_Proxy_Mapper; end Is_Proxy; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String; Attribute : in Boolean := False) return Mapper_Access is use type Ada.Strings.Unbounded.Unbounded_String; Node : Mapper_Access := Controller.First_Child; begin if Node = null and Controller.Mapper /= null then return Controller.Mapper.Find_Mapper (Name, Attribute); end if; while Node /= null loop if Node.Name = Name then if (Attribute = False and Node.Mapping = null) or else not Node.Mapping.Is_Attribute then return Node; end if; if Attribute and Node.Mapping.Is_Attribute then return Node; end if; end if; Node := Node.Next_Mapping; end loop; return null; end Find_Mapper; -- ----------------------- -- Find a path component representing a child mapper under <b>From</b> and -- identified by the given <b>Name</b>. If the mapper is not found, a new -- Mapper_Node is created. -- ----------------------- procedure Find_Path_Component (From : in out Mapper'Class; Name : in String; Result : out Mapper_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access := From.First_Child; begin if Node = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); From.First_Child := Result; return; end if; loop if Node.Name = Name then Result := Node; return; end if; if Node.Next_Mapping = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); Node.Next_Mapping := Result; return; end if; Node := Node.Next_Mapping; end loop; end Find_Path_Component; -- ----------------------- -- Build the mapping tree that corresponds to the given <b>Path</b>. -- Each path component is represented by a <b>Mapper_Node</b> element. -- The node is created if it does not exists. -- ----------------------- procedure Build_Path (Into : in out Mapper'Class; Path : in String; Last_Pos : out Natural; Node : out Mapper_Access) is Pos : Natural; begin Node := Into'Unchecked_Access; Last_Pos := Path'First; loop Pos := Util.Strings.Index (Source => Path, Char => '/', From => Last_Pos); if Pos = 0 then Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last), Result => Node); Last_Pos := Path'Last + 1; else Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1), Result => Node); Last_Pos := Pos + 1; end if; exit when Last_Pos > Path'Last; end loop; end Build_Path; -- ----------------------- -- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>. -- The <b>Path</b> string describes the matching node using a simplified XPath notation. -- Example: -- info/first_name matches: <info><first_name>...</first_name></info> -- info/a/b/name matches: <info><a><b><name>...</name></b></a></info> -- ----------------------- procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapper_Access) is Node : Mapper_Access; Last_Pos : Natural; procedure Copy (To : in Mapper_Access; From : in Mapper_Access) is N : Mapper_Access; Src : Mapper_Access := From; begin while Src /= null loop N := Src.Clone; N.Is_Clone := True; N.Next_Mapping := To.First_Child; To.First_Child := N; if Src.First_Child /= null then Copy (N, Src.First_Child); end if; Src := Src.Next_Mapping; end loop; end Copy; begin Log.Info ("Mapping {0} for mapper X", Path); -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapper /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Map.First_Child /= null then Copy (Node, Map.First_Child); else Node.Mapper := Map; end if; end Add_Mapping; procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapping_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access; Last_Pos : Natural; begin Log.Info ("Mapping {0}", Path); -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapping /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Length (Node.Name) = 0 then Log.Warn ("Mapped name is empty in mapping path {0}", Path); elsif Element (Node.Name, 1) = '@' then Delete (Node.Name, 1, 1); Map.Is_Attribute := True; else Map.Is_Attribute := False; end if; Node.Mapping := Map; Node.Mapper := Into'Unchecked_Access; end Add_Mapping; -- ----------------------- -- Clone the <b>Handler</b> instance and get a copy of that single object. -- ----------------------- function Clone (Handler : in Mapper) return Mapper_Access is Result : constant Mapper_Access := new Mapper; begin Result.Name := Handler.Name; Result.Mapper := Handler.Mapper; Result.Mapping := Handler.Mapping; Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper; Result.Is_Clone := True; return Result; end Clone; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- procedure Set_Member (Handler : in Mapper; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False; Context : in out Util.Serialize.Contexts.Context'Class) is Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute); begin if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then Map.Mapper.all.Execute (Map.Mapping.all, Context, Value); end if; end Set_Member; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Start_Object (Context, Name); end if; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Finish_Object (Context, Name); end if; end Finish_Object; -- ----------------------- -- Dump the mapping tree on the logger using the INFO log level. -- ----------------------- procedure Dump (Handler : in Mapper'Class; Log : in Util.Log.Loggers.Logger'Class; Prefix : in String := "") is procedure Dump (Map : in Mapper'Class); -- ----------------------- -- Dump the mapping description -- ----------------------- procedure Dump (Map : in Mapper'Class) is begin if Map.Mapping /= null and then Map.Mapping.Is_Attribute then Log.Info (" {0}@{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Mapping.Name)); else Log.Info (" {0}/{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Name)); Dump (Map, Log, Prefix & "/" & Ada.Strings.Unbounded.To_String (Map.Name)); end if; end Dump; begin Iterate (Handler, Dump'Access); end Dump; procedure Iterate (Controller : in Mapper; Process : not null access procedure (Map : in Mapper'Class)) is Node : Mapper_Access := Controller.First_Child; begin -- Pass 1: process the attributes first while Node /= null loop if Node.Mapping /= null and then Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; -- Pass 2: process the elements Node := Controller.First_Child; while Node /= null loop if Node.Mapping = null or else not Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; end Iterate; -- ----------------------- -- Finalize the object and release any mapping. -- ----------------------- overriding procedure Finalize (Controller : in out Mapper) is procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access); Node : Mapper_Access := Controller.First_Child; Next : Mapper_Access; begin Controller.First_Child := null; while Node /= null loop Next := Node.Next_Mapping; Free (Node); Node := Next; end loop; if not Controller.Is_Clone then Free (Controller.Mapping); else Controller.Mapping := null; end if; end Finalize; end Util.Serialize.Mappers;
Fix serialization mapping for vectors - when adding a vector mapping, do not copy the mapping but set the mapper to the vector mapping
Fix serialization mapping for vectors - when adding a vector mapping, do not copy the mapping but set the mapper to the vector mapping
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8a30186d582c7b6831c2a8d3586e1a134bc61b3a
matp/src/events/mat-events-timelines.adb
matp/src/events/mat-events-timelines.adb
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Level : in Positive; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; Limit : MAT.Types.Target_Time := MAT.Types.Target_Time (Level * 1_000_000); procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > Limit then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Event = 2 then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Event = 3 then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Event = 4 then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; First : Natural; Last : Natural; begin if Exact then First := Depth; else First := Backtrace'First; end if; if Depth < Backtrace'Last then Last := Depth; else Last := Backtrace'Last; end if; for I in First .. Last loop Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; -- ------------------------------ -- Collect the events that match the filter and append them to the events vector. -- ------------------------------ procedure Filter_Events (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Events : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is begin if Filter.Is_Selected (Event) then Events.Append (Event); end if; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Filter_Events; end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; package body MAT.Events.Timelines is use MAT.Events.Targets; ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000; procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class; Level : in Positive; Into : in out Timeline_Info_Vector) is use type MAT.Types.Target_Time; use type MAT.Types.Target_Size; procedure Collect (Event : in MAT.Events.Target_Event_Type); First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Prev_Event : MAT.Events.Target_Event_Type; Info : Timeline_Info; First_Id : MAT.Events.Event_Id_Type; Limit : MAT.Types.Target_Time := MAT.Types.Target_Time (Level * 1_000_000); procedure Collect (Event : in MAT.Events.Target_Event_Type) is Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time; begin if Dt > Limit then Into.Append (Info); Info.Malloc_Count := 0; Info.Realloc_Count := 0; Info.Free_Count := 0; Info.First_Event := Event; Info.Free_Size := 0; Info.Alloc_Size := 0; Prev_Event := Event; end if; Info.Last_Event := Event; if Event.Index = MAT.Events.MSG_MALLOC then Info.Malloc_Count := Info.Malloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; elsif Event.Index = MAT.Events.MSG_REALLOC then Info.Realloc_Count := Info.Realloc_Count + 1; Info.Alloc_Size := Info.Alloc_Size + Event.Size; Info.Free_Size := Info.Free_Size + Event.Old_Size; elsif Event.Index = MAT.Events.MSG_FREE then Info.Free_Count := Info.Free_Count + 1; Info.Free_Size := Info.Free_Size + Event.Size; end if; end Collect; begin Target.Get_Limits (First_Event, Last_Event); Prev_Event := First_Event; Info.First_Event := First_Event; First_Id := First_Event.Id; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end Extract; -- ------------------------------ -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. -- ------------------------------ procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Target_Event_Type; Max : in Positive; List : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Free (Event : in MAT.Events.Target_Event_Type); procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type); First_Id : MAT.Events.Event_Id_Type; Last_Id : MAT.Events.Event_Id_Type; First_Event : MAT.Events.Target_Event_Type; Last_Event : MAT.Events.Target_Event_Type; Addr : MAT.Types.Target_Addr := Event.Addr; Done : exception; procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Addr; end if; end Collect_Free; procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is begin if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then List.Append (Event); raise Done; end if; if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then List.Append (Event); if Positive (List.Length) >= Max then raise Done; end if; Addr := Event.Old_Addr; end if; end Collect_Alloc; begin Target.Get_Limits (First_Event, Last_Event); First_Id := Event.Id; if Event.Index = MAT.Events.MSG_FREE then -- Search backward for MSG_MALLOC and MSG_REALLOC. First_Id := First_Id - 1; while First_Id > First_Event.Id loop if First_Id > ITERATE_COUNT then Last_Id := First_Id - ITERATE_COUNT; else Last_Id := First_Event.Id; end if; Target.Iterate (Start => First_Id, Finish => Last_Id, Process => Collect_Alloc'Access); First_Id := Last_Id; end loop; else -- Search forward for MSG_REALLOC and MSG_FREE First_Id := First_Id + 1; while First_Id < Last_Event.Id loop Target.Iterate (Start => First_Id, Finish => First_Id + ITERATE_COUNT, Process => Collect_Free'Access); First_Id := First_Id + ITERATE_COUNT; end loop; end if; exception when Done => null; end Find_Related; -- ------------------------------ -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. -- ------------------------------ procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Tools.Size_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Size : in MAT.Types.Target_Size; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Size); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for malloc or realloc events which are selected by the filter. if (Event.Index /= MAT.Events.MSG_MALLOC and Event.Index /= MAT.Events.MSG_FREE and Event.Index /= MAT.Events.MSG_REALLOC) or else not Filter.Is_Selected (Event) then return; end if; declare Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size); begin if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Sizes.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; MAT.Events.Tools.Collect_Info (Info, Event); Sizes.Insert (Event.Size, Info); end; end if; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Sizes; -- ------------------------------ -- Find the function address from the call event frames for the events which is selected -- by the given filter. The function addresses are collected up to the given frame depth. -- Update the <tt>Frames</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding frame address. -- ------------------------------ procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Depth : in Positive; Exact : in Boolean; Frames : in out MAT.Events.Tools.Frame_Event_Info_Map) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type); procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type; Info : in out MAT.Events.Tools.Event_Info_Type) is pragma Unreferenced (Key); begin MAT.Events.Tools.Collect_Info (Info, Event); end Update_Size; begin -- Look for events which are selected by the filter. if not Filter.Is_Selected (Event) then return; end if; declare Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame); Key : MAT.Events.Tools.Frame_Key_Type; First : Natural; Last : Natural; begin if Exact then First := Depth; else First := Backtrace'First; end if; if Depth < Backtrace'Last then Last := Depth; else Last := Backtrace'Last; end if; for I in First .. Last loop Key.Addr := Backtrace (Backtrace'Last - I + 1); Key.Level := I; declare Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor := Frames.Find (Key); begin if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then -- Increment the count and update the last event. Frames.Update_Element (Pos, Update_Size'Access); else declare Info : MAT.Events.Tools.Event_Info_Type; begin -- Insert a new size with the event. Info.First_Event := Event; Info.Count := 0; MAT.Events.Tools.Collect_Info (Info, Event); Frames.Insert (Key, Info); end; end if; end; end loop; end; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Find_Frames; -- ------------------------------ -- Collect the events that match the filter and append them to the events vector. -- ------------------------------ procedure Filter_Events (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Events : in out MAT.Events.Tools.Target_Event_Vector) is procedure Collect_Event (Event : in MAT.Events.Target_Event_Type); procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is begin if Filter.Is_Selected (Event) then Events.Append (Event); end if; end Collect_Event; begin Target.Iterate (Process => Collect_Event'Access); end Filter_Events; end MAT.Events.Timelines;
Use the Probe_Index_Type enum values to analyze the timeline event
Use the Probe_Index_Type enum values to analyze the timeline event
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d4d805e9cce3dfdcd3488a97d9f6661b1ca537bf
awa/src/awa-users-principals.adb
awa/src/awa-users-principals.adb
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- package body AWA.Users.Principals is -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return From.User.Get_Name; end Get_Name; -- ------------------------------ -- 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 is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal identifier (name) -- ------------------------------ function Get_Id (From : in Principal) return String is begin return From.User.Get_Name; end Get_Id; -- ------------------------------ -- Get the user associated with the principal. -- ------------------------------ function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is begin return From.User; end Get_User; -- ------------------------------ -- 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 is begin return From.User.Get_Id; end Get_User_Identifier; -- ------------------------------ -- Get the connection session used by the user. -- ------------------------------ function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is begin return From.Session; end Get_Session; -- ------------------------------ -- Get the connection session identifier used by the user. -- ------------------------------ function Get_Session_Identifier (From : in Principal) return ADO.Identifier is begin return From.Session.Get_Id; end Get_Session_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 is Result : constant Principal_Access := new Principal; begin Result.User := User; Result.Session := Session; return Result; end Create; -- ------------------------------ -- 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 is use type Security.Permissions.Principal_Access; begin if From = null then return ADO.NO_IDENTIFIER; elsif not (From.all in Principal'Class) then return ADO.NO_IDENTIFIER; else return Principal'Class (From.all).Get_User_Identifier; end if; end Get_User_Identifier; 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. ----------------------------------------------------------------------- package body AWA.Users.Principals is -- ------------------------------ -- Get the principal name. -- ------------------------------ function Get_Name (From : in Principal) return String is begin return From.User.Get_Name; end Get_Name; -- ------------------------------ -- 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 is begin return User.Roles (Role); end Has_Role; -- ------------------------------ -- Get the principal identifier (name) -- ------------------------------ function Get_Id (From : in Principal) return String is begin return From.User.Get_Name; end Get_Id; -- ------------------------------ -- Get the user associated with the principal. -- ------------------------------ function Get_User (From : in Principal) return AWA.Users.Models.User_Ref is begin return From.User; end Get_User; -- ------------------------------ -- 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 is begin return From.User.Get_Id; end Get_User_Identifier; -- ------------------------------ -- Get the connection session used by the user. -- ------------------------------ function Get_Session (From : in Principal) return AWA.Users.Models.Session_Ref is begin return From.Session; end Get_Session; -- ------------------------------ -- Get the connection session identifier used by the user. -- ------------------------------ function Get_Session_Identifier (From : in Principal) return ADO.Identifier is begin return From.Session.Get_Id; end Get_Session_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 is Result : constant Principal_Access := new Principal; begin Result.User := User; Result.Session := Session; return Result; end Create; -- ------------------------------ -- 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 is use type ASF.Principals.Principal_Access; begin if From = null then return ADO.NO_IDENTIFIER; elsif not (From.all in Principal'Class) then return ADO.NO_IDENTIFIER; else return Principal'Class (From.all).Get_User_Identifier; end if; end Get_User_Identifier; end AWA.Users.Principals;
Use ASF.Principals definition
Use ASF.Principals definition
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
a0e50548d231816df551f4693e5b4abf8aa09fe1
src/security-policies-urls.ads
src/security-policies-urls.ads
----------------------------------------------------------------------- -- 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.Strings; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Contexts; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URL_Permission</tt> object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Reader : in out Util.Serialize.IO.XML.Parser); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.URLs;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.Mappers; with GNAT.Regexp; with Security.Contexts; -- == URL Security Policy == -- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === Policy creation === -- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. -- These two permissions are checked according to another security policy. -- The XML configuration can define several <tt>url-policy</tt>. They are checked in -- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches -- the URL is used to verify the permission. -- -- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a <tt>URL_Permission</tt> object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Mapper : in out Util.Serialize.Mappers.Processing); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); type Rules_Ref_Access is access Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.URLs;
Change the Mapper parameter to use the Mappers.Processing type
Change the Mapper parameter to use the Mappers.Processing type
Ada
apache-2.0
stcarrez/ada-security
f7438721836603d7613079af4fdf5c2bb940b252
src/os-linux/util-systems-os.ads
src/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type File_Type is new Integer; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Interfaces.C.int) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type File_Type is new Integer; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Interfaces.C.int) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME); function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; pragma Import (C, Sys_Lseek, "lseek"); end Util.Systems.Os;
Declare Sys_Lseek import definition
Declare Sys_Lseek import definition
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8ef9da1f9b7f74b5c87c4f3c53e01038a82c679e
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
awa/plugins/awa-workspaces/src/awa-workspaces-beans.ads
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_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 Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; end record; -- Load the list of members. overriding procedure Load (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); end AWA.Workspaces.Beans;
----------------------------------------------------------------------- -- awa-workspaces-beans -- Beans for module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with Util.Beans.Methods; with AWA.Events; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; package AWA.Workspaces.Beans is type Invitation_Bean is new AWA.Workspaces.Models.Invitation_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; end record; type Invitation_Bean_Access is access all Invitation_Bean'Class; overriding procedure Load (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Accept_Invitation (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); overriding procedure Send (Bean : in out Invitation_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Workspaces_Bean is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access := null; Count : Natural := 0; end record; type Workspaces_Bean_Access is access all Workspaces_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Workspaces_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Workspaces_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 Workspaces_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Event action called to create the workspace when the given event is posted. procedure Create (Bean : in out Workspaces_Bean; Event : in AWA.Events.Module_Event'Class); -- Example of action method. procedure Action (Bean : in out Workspaces_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Workspaces_Bean bean instance. function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Member_List_Bean is new AWA.Workspaces.Models.Member_List_Bean with record Module : AWA.Workspaces.Modules.Workspace_Module_Access; -- The list of workspace members. Members : aliased AWA.Workspaces.Models.Member_Info_List_Bean; Members_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); end AWA.Workspaces.Beans;
Add Members and Members_Bean to the Member_List_Bean type
Add Members and Members_Bean to the Member_List_Bean type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8f6b3a736946c797b2ab2ebce701a9ab4259f42f
awa/plugins/awa-storages/src/awa-storages-beans.adb
awa/plugins/awa-storages/src/awa-storages-beans.adb
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016, 2018, 2019, 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 Util.Log.Loggers; with Util.Strings; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; use type ADO.Identifier; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part); exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin if Storage.Folder_Id /= ADO.NO_IDENTIFIER then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_Id); elsif Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then From.Folder_Id := ADO.Utils.To_Identifier (Value); end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then return Util.Beans.Objects.To_Object (Value => List.Files_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 List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Folder; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; -- ------------------------------ -- Returns true if the given mime type can be displayed by a browser. -- Mime types: application/pdf, text/*, image/* -- ------------------------------ function Is_Browser_Visible (Mime_Type : in String) return Boolean is begin if Mime_Type = "application/pdf" then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "text/") then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "image/") then return True; end if; return False; end Is_Browser_Visible; overriding function Get_Value (From : in Storage_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "isBrowserVisible" then return Util.Beans.Objects.To_Object (Is_Browser_Visible (To_String (From.Mime_Type))); else return AWA.Storages.Models.Storage_Bean (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Storages.Models.Query_Storage_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Storage_Bean bean instance. -- ------------------------------ function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_Bean_Access := new Storage_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Storage_Bean; end AWA.Storages.Beans;
----------------------------------------------------------------------- -- awa-storages-beans -- Storage Ada Beans -- Copyright (C) 2012, 2013, 2016, 2018, 2019, 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 Util.Log.Loggers; with Util.Strings; with ADO.Utils; with ADO.Queries; with ADO.Sessions; with ADO.Objects; with AWA.Permissions; with AWA.Helpers.Requests; with AWA.Services.Contexts; with AWA.Storages.Services; package body AWA.Storages.Beans is use Ada.Strings.Unbounded; use type ADO.Identifier; package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Beans"); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Upload_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "folderId" then return ADO.Utils.To_Object (From.Folder_Id); elsif From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Upload_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is Manager : constant Services.Storage_Service_Access := From.Module.Get_Storage_Manager; Folder : Models.Storage_Folder_Ref; Found : Boolean; Id : ADO.Identifier; begin if Name = "folderId" then From.Folder_Id := ADO.Utils.To_Identifier (Value); Manager.Load_Folder (Folder, From.Folder_Id); From.Set_Folder (Folder); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then Id := ADO.Utils.To_Identifier (Value); if Id /= ADO.NO_IDENTIFIER then Manager.Load_Storage (From, Id); end if; elsif Name = "name" then Folder := Models.Storage_Folder_Ref (From.Get_Folder); Manager.Load_Storage (From, From.Folder_Id, Util.Beans.Objects.To_String (Value), Found); if not Found then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; From.Set_Folder (Folder); end if; end Set_Value; -- ------------------------------ -- Save the uploaded file in the storage service. -- ------------------------------ procedure Save_Part (Bean : in out Upload_Bean; Part : in ASF.Parts.Part'Class) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Name : constant String := Bean.Get_Name; begin if Name'Length = 0 then Bean.Set_Name (Part.Get_Name); end if; Bean.Set_Mime_Type (Part.Get_Content_Type); Bean.Set_File_Size (Part.Get_Size); Manager.Save (Bean, Part); exception when AWA.Permissions.NO_PERMISSION => Bean.Error := True; Log.Error ("Saving document is refused by the permission controller"); raise; when E : others => Bean.Error := True; Log.Error ("Exception when saving the document", E); raise; end Save_Part; -- ------------------------------ -- Upload the file. -- ------------------------------ procedure Upload (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Outcome := To_Unbounded_String (if Bean.Error then "failure" else "success"); end Upload; -- ------------------------------ -- Delete the file. -- ------------------------------ procedure Delete (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Delete (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Delete; -- ------------------------------ -- Publish the file. -- ------------------------------ overriding procedure Publish (Bean : in out Upload_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Manager.Publish (Id, Util.Beans.Objects.To_Boolean (Value), Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Publish; -- ------------------------------ -- Create the Upload_Bean bean instance. -- ------------------------------ function Create_Upload_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Upload_Bean_Access := new Upload_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Upload_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Folder_Bean; Name : in String) return Util.Beans.Objects.Object is begin if ADO.Objects.Is_Null (From) then return Util.Beans.Objects.Null_Object; else return AWA.Storages.Models.Storage_Folder_Ref (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Folder_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; -- ------------------------------ -- Create or save the folder. -- ------------------------------ overriding procedure Save (Bean : in out Folder_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Storage_Service_Access := Bean.Module.Get_Storage_Manager; begin Manager.Save_Folder (Bean); Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); end Save; -- ------------------------------ -- Create the Folder_Bean bean instance. -- ------------------------------ function Create_Folder_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Folder_Bean_Access := new Folder_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Folder_Bean; -- ------------------------------ -- Load the folder instance. -- ------------------------------ procedure Load_Folder (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use type Ada.Containers.Count_Type; Manager : constant Services.Storage_Service_Access := Storage.Module.Get_Storage_Manager; begin if Storage.Folder_Id /= ADO.NO_IDENTIFIER then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_Id); elsif Storage.Folder_List.List.Length > 0 then Manager.Load_Folder (Storage.Folder_Bean.all, Storage.Folder_List.List.Element (1).Id); end if; Storage.Flags (INIT_FOLDER) := True; end Load_Folder; -- ------------------------------ -- Load the list of folders. -- ------------------------------ procedure Load_Folders (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Storage.Folder_List_Bean.all, Session, Query); Storage.Flags (INIT_FOLDER_LIST) := True; end Load_Folders; -- ------------------------------ -- Load the list of files associated with the current folder. -- ------------------------------ procedure Load_Files (Storage : in out Storage_List_Bean) is use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if not Storage.Init_Flags (INIT_FOLDER) then Load_Folder (Storage); end if; Query.Set_Query (AWA.Storages.Models.Query_Storage_List); Query.Bind_Param ("user_id", User); if Storage.Folder_Bean.Is_Null then Query.Bind_Null_Param ("folder_id"); else Query.Bind_Param ("folder_id", Storage.Folder_Bean.Get_Id); end if; AWA.Storages.Models.List (Storage.Files_List_Bean.all, Session, Query); Storage.Flags (INIT_FILE_LIST) := True; end Load_Files; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Storage_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "folderId" and not Util.Beans.Objects.Is_Empty (Value) then From.Folder_Id := ADO.Utils.To_Identifier (Value); end if; end Set_Value; overriding function Get_Value (List : in Storage_List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "files" then return Util.Beans.Objects.To_Object (Value => List.Files_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 List.Folder_Bean.Is_Null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (Value => List.Folder_Bean, Storage => Util.Beans.Objects.STATIC); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Load the files and folder information. -- ------------------------------ overriding procedure Load (List : in out Storage_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Storage_List_Bean'Class (List).Load_Folders; Storage_List_Bean'Class (List).Load_Folder; Storage_List_Bean'Class (List).Load_Files; end Load; -- ------------------------------ -- Create the Folder_List_Bean bean instance. -- ------------------------------ function Create_Folder_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is pragma Unreferenced (Module); use AWA.Storages.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Folder_Info_List_Bean_Access := new Folder_Info_List_Bean; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Storages.Models.Query_Storage_Folder_List); Query.Bind_Param ("user_id", User); AWA.Storages.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Folder_List_Bean; -- ------------------------------ -- Create the Storage_List_Bean bean instance. -- ------------------------------ function Create_Storage_List_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_List_Bean_Access := new Storage_List_Bean; begin Object.Module := Module; Object.Folder_Bean := Object.Folder'Access; Object.Folder_List_Bean := Object.Folder_List'Access; Object.Files_List_Bean := Object.Files_List'Access; Object.Flags := Object.Init_Flags'Access; return Object.all'Access; end Create_Storage_List_Bean; -- ------------------------------ -- Returns true if the given mime type can be displayed by a browser. -- Mime types: application/pdf, text/*, image/* -- ------------------------------ function Is_Browser_Visible (Mime_Type : in String) return Boolean is begin if Mime_Type = "application/pdf" then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "text/") then return True; end if; if Util.Strings.Starts_With (Mime_Type, Prefix => "image/") then return True; end if; return False; end Is_Browser_Visible; overriding function Get_Value (From : in Storage_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "isBrowserVisible" then return Util.Beans.Objects.To_Object (Is_Browser_Visible (To_String (From.Mime_Type))); else return AWA.Storages.Models.Storage_Bean (From).Get_Value (Name); end if; end Get_Value; overriding procedure Load (Into : in out Storage_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Ctx : constant ASC.Service_Context_Access := ASC.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Session : ADO.Sessions.Session := ASC.Get_Session (Ctx); Query : ADO.Queries.Context; begin if Into.Id = ADO.NO_IDENTIFIER then Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); return; end if; -- Get the image information. Query.Set_Query (AWA.Storages.Models.Query_Storage_Info); Query.Bind_Param (Name => "user_id", Value => User); Query.Bind_Param (Name => "file_id", Value => Into.Id); Into.Load (Session, Query); exception when ADO.Objects.NOT_FOUND => Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found"); end Load; -- ------------------------------ -- Create the Storage_Bean bean instance. -- ------------------------------ function Create_Storage_Bean (Module : in AWA.Storages.Modules.Storage_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Storage_Bean_Access := new Storage_Bean; begin Object.Module := Module; Object.Id := ADO.NO_IDENTIFIER; return Object.all'Access; end Create_Storage_Bean; end AWA.Storages.Beans;
Implement Create_Folder_Bean function
Implement Create_Folder_Bean function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d4ee99ff823710c52a7820a3852f8ca107fb45ad
src/util-beans-objects-lists.adb
src/util-beans-objects-lists.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Lists -- List bean holding some object -- 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. ----------------------------------------------------------------------- package body Util.Beans.Objects.Lists is -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ function Get_Count (From : in List_Bean) return Natural is begin return Natural (Vectors.Length (From.List)); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is begin From.Current := Index; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is begin return Vectors.Element (From.List, From.Current - 1); end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : in List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.List.Length)); elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Current); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; end Util.Beans.Objects.Lists;
----------------------------------------------------------------------- -- Util.Beans.Objects.Lists -- List bean holding some object -- 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. ----------------------------------------------------------------------- package body Util.Beans.Objects.Lists is -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ function Get_Count (From : in List_Bean) return Natural is begin return Natural (Vectors.Length (From.List)); end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is begin From.Current := Index; end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object is begin return Vectors.Element (From.List, From.Current); end Get_Row; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ function Get_Value (From : in List_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.List.Length)); elsif Name = "rowIndex" then return Util.Beans.Objects.To_Object (From.Current); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; end Util.Beans.Objects.Lists;
Update Get_Row now that we are using positive indexes
Update Get_Row now that we are using positive indexes
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a2033bdee75ddf6a58e9125cc9074bd8d33e9e77
src/base/commands/util-commands-parsers-gnat_parser.adb
src/base/commands/util-commands-parsers-gnat_parser.adb
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- 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 GNAT.OS_Lib; package body Util.Commands.Parsers.GNAT_Parser is function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access; function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access is Count : constant Natural := Args.Get_Count; New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count); begin for I in 1 .. Count loop New_Arg (I) := new String '(Args.Get_Argument (I)); end loop; return new GNAT.OS_Lib.Argument_List '(New_Arg); end To_OS_Lib_Argument_List; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is use type GNAT.Command_Line.Command_Line_Configuration; Empty : Config_Type; begin if Config /= Empty then declare Parser : GNAT.Command_Line.Opt_Parser; Cmd_Args : Dynamic_Argument_List; Params : GNAT.OS_Lib.Argument_List_Access := To_OS_Lib_Argument_List (Args); begin GNAT.Command_Line.Initialize_Option_Scan (Parser, Params); GNAT.Command_Line.Getopt (Config => Config, Parser => Parser); Cmd_Args.Name := Ada.Strings.Unbounded.To_Unbounded_String (Args.Get_Command_Name); loop declare S : constant String := GNAT.Command_Line.Get_Argument (Parser => Parser); begin exit when S'Length = 0; Cmd_Args.List.Append (S); end; end loop; Process (Cmd_Args); GNAT.Command_Line.Free (Config); GNAT.OS_Lib.Free (Params); exception when others => GNAT.OS_Lib.Free (Params); GNAT.Command_Line.Free (Config); raise; end; else Process (Args); end if; end Execute; procedure Usage (Name : in String; Config : in out Config_Type) is begin GNAT.Command_Line.Set_Usage (Config, Usage => Name & " [switches] [arguments]"); GNAT.Command_Line.Display_Help (Config); end Usage; end Util.Commands.Parsers.GNAT_Parser;
----------------------------------------------------------------------- -- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.OS_Lib; package body Util.Commands.Parsers.GNAT_Parser is function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access; function To_OS_Lib_Argument_List (Args : in Argument_List'Class) return GNAT.OS_Lib.Argument_List_Access is Count : constant Natural := Args.Get_Count; New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count); begin for I in 1 .. Count loop New_Arg (I) := new String '(Args.Get_Argument (I)); end loop; return new GNAT.OS_Lib.Argument_List '(New_Arg); end To_OS_Lib_Argument_List; -- ------------------------------ -- Get all the remaining arguments from the GNAT command line parse. -- ------------------------------ procedure Get_Arguments (List : in out Dynamic_Argument_List; Command : in String; Parser : in GC.Opt_Parser := GC.Command_Line_Parser) is begin List.Name := Ada.Strings.Unbounded.To_Unbounded_String (Command); loop declare S : constant String := GC.Get_Argument (Parser => Parser); begin exit when S'Length = 0; List.List.Append (S); end; end loop; end Get_Arguments; procedure Execute (Config : in out Config_Type; Args : in Util.Commands.Argument_List'Class; Process : access procedure (Cmd_Args : in Commands.Argument_List'Class)) is use type GC.Command_Line_Configuration; Empty : Config_Type; begin if Config /= Empty then declare Parser : GC.Opt_Parser; Cmd_Args : Dynamic_Argument_List; Params : GNAT.OS_Lib.Argument_List_Access := To_OS_Lib_Argument_List (Args); begin GC.Initialize_Option_Scan (Parser, Params); GC.Getopt (Config => Config, Parser => Parser); Get_Arguments (Cmd_Args, Args.Get_Command_Name, Parser); Process (Cmd_Args); GC.Free (Config); GNAT.OS_Lib.Free (Params); exception when others => GNAT.OS_Lib.Free (Params); GC.Free (Config); raise; end; else Process (Args); end if; end Execute; procedure Usage (Name : in String; Config : in out Config_Type) is begin GC.Set_Usage (Config, Usage => Name & " [switches] [arguments]"); GC.Display_Help (Config); end Usage; end Util.Commands.Parsers.GNAT_Parser;
Implement the Get_Arguments procedure and use it
Implement the Get_Arguments procedure and use it
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c328e742ae412f85669f83a970ff17dc5b8d4527
src/bbox-api.ads
src/bbox-api.ads
----------------------------------------------------------------------- -- bbox -- Bbox API -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Properties; with Util.Http.Clients; package Bbox.API is type Client_Type is tagged limited private; -- Set the server IP address. procedure Set_Server (Client : in out Client_Type; Server : in String); -- Login to the server Bbox API with the password. procedure Login (Client : in out Client_Type; Password : in String); -- Execute a GET operation on the Bbox API to retrieve the result into the property list. procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager); private -- Internal operation to get the URI based on the operation being called. function Get_URI (Client : in Client_Type; Operation : in String) return String; type Client_Type is tagged limited record Password : Ada.Strings.Unbounded.Unbounded_String; Server : Ada.Strings.Unbounded.Unbounded_String; Auth : Ada.Strings.Unbounded.Unbounded_String; Http : Util.Http.Clients.Client; end record; end Bbox.API;
----------------------------------------------------------------------- -- bbox -- Bbox API -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Properties; with Util.Http.Clients; package Bbox.API is type Client_Type is tagged limited private; -- Set the server IP address. procedure Set_Server (Client : in out Client_Type; Server : in String); -- Login to the server Bbox API with the password. procedure Login (Client : in out Client_Type; Password : in String); -- Execute a GET operation on the Bbox API to retrieve the result into the property list. procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager); -- Execute a GET operation on the Bbox API to retrieve the JSON result and return it. function Get (Client : in out Client_Type; Operation : in String) return String; private -- Internal operation to get the URI based on the operation being called. function Get_URI (Client : in Client_Type; Operation : in String) return String; type Client_Type is tagged limited record Password : Ada.Strings.Unbounded.Unbounded_String; Server : Ada.Strings.Unbounded.Unbounded_String; Auth : Ada.Strings.Unbounded.Unbounded_String; Http : Util.Http.Clients.Client; end record; end Bbox.API;
Declare the Get function to call a Bbox API and get the JSON raw result
Declare the Get function to call a Bbox API and get the JSON raw result
Ada
apache-2.0
stcarrez/bbox-ada-api
550b9f66fe822333c37450830c9ea0d33f1f1970
src/el-beans.ads
src/el-beans.ads
----------------------------------------------------------------------- -- EL.Beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package EL.Beans is -- Exception raised when the value identified by a name is not -- recognized. No_Value : exception; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return EL.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is interface and Readonly_Bean; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. function Get_Count (From : List_Bean) return Natural is abstract; -- Get the element at the given index. function Get_Row (From : List_Bean; Index : Natural) return EL.Objects.Object is abstract; end EL.Beans;
----------------------------------------------------------------------- -- EL.Beans -- Interface Definition with Getter and Setters -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package EL.Beans is -- Exception raised when the value identified by a name is not -- recognized. No_Value : exception; -- ------------------------------ -- Read-only Bean interface. -- ------------------------------ -- The ''Readonly_Bean'' interface allows to plug a complex -- runtime object to the expression resolver. This interface -- must be implemented by any tagged record that should be -- accessed as a variable for an expression. -- -- For example, if 'foo' is bound to an object implementing that -- interface, expressions like 'foo.name' will resolve to 'foo' -- and the 'Get_Value' method will be called with 'name'. -- type Readonly_Bean is interface; type Readonly_Bean_Access is access all Readonly_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : Readonly_Bean; Name : String) return EL.Objects.Object is abstract; -- ------------------------------ -- Bean interface. -- ------------------------------ -- The ''Bean'' interface allows to modify a property value. type Bean is interface and Readonly_Bean; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. procedure Set_Value (From : in out Bean; Name : in String; Value : in EL.Objects.Object) is abstract; -- ------------------------------ -- List of objects -- ------------------------------ -- The <b>List_Bean</b> interface gives access to a list of objects. type List_Bean is interface and Readonly_Bean; type List_Bean_Access is access all List_Bean'Class; -- Get the number of elements in the list. function Get_Count (From : List_Bean) return Natural is abstract; -- Set the current row index. Valid row indexes start at 1. procedure Set_Row_Index (From : in out List_Bean; Index : in Natural) is abstract; -- Get the element at the current row index. function Get_Row (From : List_Bean) return EL.Objects.Object is abstract; end EL.Beans;
Change the List bean interface to follow JSF DataModel interface - invoke Set_Row_Index to tell the bean the current index (the bean in an 'in out' parameter) - invoke Get_Row to get the current row (the bean is an 'in' parameter)
Change the List bean interface to follow JSF DataModel interface - invoke Set_Row_Index to tell the bean the current index (the bean in an 'in out' parameter) - invoke Get_Row to get the current row (the bean is an 'in' parameter)
Ada
apache-2.0
stcarrez/ada-el
355e5da71bd6919cc6395b05bac65ff9d1c68144
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.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; 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 : aliased MAT.Events.Targets.Target_Events; 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;
Add the Target_Events instance in the Target_Process_Type record
Add the Target_Events instance in the Target_Process_Type record
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
cf9580be61cf47a7d21fb3714df9aec22e2f1b1b
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 MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited 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; -- 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; 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; 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 tagged limited record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; 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 MAT.Types; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Readers; with MAT.Consoles; package MAT.Targets is type Target_Process_Type is tagged limited record Pid : MAT.Types.Target_Process_Ref; Memory : MAT.Memory.Targets.Target_Memory; Symbols : MAT.Symbols.Targets.Target_Symbols_Ref; Console : MAT.Consoles.Console_Access; end record; type Target_Process_Type_Access is access all Target_Process_Type'Class; type Target_Type is tagged limited 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; -- 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; 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; 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 tagged limited record Current : Target_Process_Type_Access; Processes : Process_Map; Console : MAT.Consoles.Console_Access; end record; end MAT.Targets;
Add a symbols object in the target process
Add a symbols object in the target process
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c3a48b16fee3486f58e84912a78c78267cd4c8e7
src/babel-base-text.adb
src/babel-base-text.adb
----------------------------------------------------------------------- -- babel-base -- Database for files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Dates.ISO8601; with Babel.Files.Sets; with Babel.Files.Lifecycles; with Ada.Text_IO; package body Babel.Base.Text is -- ------------------------------ -- Insert the file in the database. -- ------------------------------ overriding procedure Insert (Into : in out Text_Database; File : in Babel.Files.File_Type) is begin Into.Files.Insert (File); end Insert; -- ------------------------------ -- Write the SHA1 checksum for the files stored in the map. -- ------------------------------ procedure Save (Database : in Text_Database; Path : in String) is Checksum : Ada.Text_IO.File_Type; procedure Write_Checksum (Position : in Babel.Files.Sets.File_Cursor) is File : constant Babel.Files.File_Type := Babel.Files.Sets.File_Sets.Element (Position); SHA1 : constant String := Babel.Files.Get_SHA1 (File); Path : constant String := Babel.Files.Get_Path (File); begin Ada.Text_IO.Put (Checksum, SHA1); Ada.Text_IO.Put (Checksum, Babel.Uid_Type'Image (Babel.Files.Get_User (File))); Ada.Text_IO.Put (Checksum, Babel.Gid_Type'Image (Babel.Files.Get_Group (File))); Ada.Text_IO.Put (Checksum, " "); Ada.Text_IO.Put (Checksum, Util.Dates.ISO8601.Image (Babel.Files.Get_Date (File))); Ada.Text_IO.Put (Checksum, Babel.Files.File_Size'Image (Babel.Files.Get_Size (File))); Ada.Text_IO.Put (Checksum, " "); Ada.Text_IO.Put (Checksum, Path); Ada.Text_IO.New_Line (Checksum); end Write_Checksum; begin Ada.Text_IO.Create (File => Checksum, Name => Path); Database.Files.Iterate (Write_Checksum'Access); Ada.Text_IO.Close (File => Checksum); end Save; end Babel.Base.Text;
----------------------------------------------------------------------- -- babel-base -- Database for files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Dates.ISO8601; with Babel.Files.Sets; with Babel.Files.Lifecycles; with Ada.Text_IO; package body Babel.Base.Text is -- ------------------------------ -- Insert the file in the database. -- ------------------------------ overriding procedure Insert (Into : in out Text_Database; File : in Babel.Files.File_Type) is begin Into.Files.Insert (File); end Insert; overriding procedure Iterate (From : in Text_Database; Process : not null access procedure (File : in Babel.Files.File_Type)) is procedure Process_One (Pos : in Babel.Files.Sets.File_Cursor) is begin Process (Babel.Files.Sets.File_Sets.Element (Pos)); end Process_One; begin From.Files.Iterate (Process_One'Access); end Iterate; -- ------------------------------ -- Write the SHA1 checksum for the files stored in the map. -- ------------------------------ procedure Save (Database : in Text_Database; Path : in String) is Checksum : Ada.Text_IO.File_Type; procedure Write_Checksum (Position : in Babel.Files.Sets.File_Cursor) is File : constant Babel.Files.File_Type := Babel.Files.Sets.File_Sets.Element (Position); SHA1 : constant String := Babel.Files.Get_SHA1 (File); Path : constant String := Babel.Files.Get_Path (File); begin Ada.Text_IO.Put (Checksum, SHA1); Ada.Text_IO.Put (Checksum, Babel.Uid_Type'Image (Babel.Files.Get_User (File))); Ada.Text_IO.Put (Checksum, Babel.Gid_Type'Image (Babel.Files.Get_Group (File))); Ada.Text_IO.Put (Checksum, " "); Ada.Text_IO.Put (Checksum, Util.Dates.ISO8601.Image (Babel.Files.Get_Date (File))); Ada.Text_IO.Put (Checksum, Babel.Files.File_Size'Image (Babel.Files.Get_Size (File))); Ada.Text_IO.Put (Checksum, " "); Ada.Text_IO.Put (Checksum, Path); Ada.Text_IO.New_Line (Checksum); end Write_Checksum; begin Ada.Text_IO.Create (File => Checksum, Name => Path); Database.Files.Iterate (Write_Checksum'Access); Ada.Text_IO.Close (File => Checksum); end Save; end Babel.Base.Text;
Implement the Iterate procedure
Implement the Iterate procedure
Ada
apache-2.0
stcarrez/babel
a5ed93536c00c5f4c9c8cc195d3cc64ab3c72f67
awa/plugins/awa-votes/src/awa-votes-modules.ads
awa/plugins/awa-votes/src/awa-votes-modules.ads
----------------------------------------------------------------------- -- 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 ASF.Applications; with ADO; with AWA.Modules; -- == Integration == -- The <tt>Vote_Module</tt> manages the votes on entities. It provides operations that are -- used by the vote beans or other services to vote for an item. An instance of the -- the <tt>Vote_Module</tt> must be declared and registered in the AWA application. -- package AWA.Votes.Modules is -- The name under which the module is registered. NAME : constant String := "votes"; -- ------------------------------ -- Module votes -- ------------------------------ type Vote_Module is new AWA.Modules.Module with private; type Vote_Module_Access is access all Vote_Module'Class; -- Initialize the votes module. overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the votes module. function Get_Vote_Module return Vote_Module_Access; -- 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); private type Vote_Module is new AWA.Modules.Module with null record; 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 ASF.Applications; with ADO; with AWA.Modules; -- == Integration == -- The <tt>Vote_Module</tt> manages the votes on entities. It provides operations that are -- used by the vote beans or other services to vote for an item. An instance of the -- the <tt>Vote_Module</tt> must be declared and registered in the AWA application. -- The module instance can be defined as follows: -- -- type Application is new AWA.Applications.Application with record -- Vote_Module : aliased AWA.Votes.Modules.Vote_Module; -- end record; -- -- And registered in the `Initialize_Modules` procedure by using: -- -- Register (App => App.Self.all'Access, -- Name => AWA.Votes.Modules.NAME, -- URI => "votes", -- Module => App.Vote_Module'Access); package AWA.Votes.Modules is -- The name under which the module is registered. NAME : constant String := "votes"; -- ------------------------------ -- Module votes -- ------------------------------ type Vote_Module is new AWA.Modules.Module with private; type Vote_Module_Access is access all Vote_Module'Class; -- Initialize the votes module. overriding procedure Initialize (Plugin : in out Vote_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the votes module. function Get_Vote_Module return Vote_Module_Access; -- 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); private type Vote_Module is new AWA.Modules.Module with null record; end AWA.Votes.Modules;
Document the vote module registration
Document the vote module registration
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8f4dae92a230165fc93315f5dac6016f5a6338f4
src/gen-generator.ads
src/gen-generator.ads
----------------------------------------------------------------------- -- gen-generator -- Code Generator -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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; 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 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 : access Util.Beans.Objects.Object; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : access Util.Beans.Objects.Object; -- 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 : access Util.Beans.Objects.Object; -- 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; -- 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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 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 : access Util.Beans.Objects.Object; -- Indicates whether the file must be saved at each generation or only once. -- This is the mode attribute in <f:view>. Mode : access Util.Beans.Objects.Object; -- 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 : access Util.Beans.Objects.Object; -- 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;
Add the YAML artifact
Add the YAML artifact
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
f3a47801e190b438a14590dcbcb5269300302de3
src/dbmapper.adb
src/dbmapper.adb
----------------------------------------------------------------------- -- dbmapper -- Database Mapper Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Sax.Readers; use Sax.Readers; with Ada.Text_IO; with Ada.Exceptions; with Ada.Command_Line; with Gen.Generator; procedure DBMapper is use Ada; use Ada.Command_Line; Generator : Gen.Generator.Handler; Release : constant String := "ADO Generator 0.2, Stephane Carrez"; Copyright : constant String := "Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc."; ----------------- -- Output_File -- ----------------- -------------------------------------------------- -- Usage -------------------------------------------------- procedure Usage is use Ada.Text_IO; begin Put_Line (Release); Put_Line (Copyright); New_Line; Put ("Usage: "); Put (Command_Name); Put_Line (" [-v] [-o directory] [-t templates] model.xml"); Put_Line ("where:"); Put_Line (" -v Verbose"); Put_Line (" -q Query mode"); Put_Line (" -o directory Directory where the Ada mapping files are generated"); Put_Line (" -t templates Directory where the Ada templates are defined"); New_Line; Put_Line (" -h Requests this info."); New_Line; end Usage; begin -- Parse the command line loop case Getopt ("o: t:") is when ASCII.Nul => exit; when 'o' => Gen.Generator.Set_Result_Directory (Generator, Parameter & "/"); when 't' => Gen.Generator.Set_Template_Directory (Generator, Parameter & "/"); when others => null; end case; end loop; declare Model_File : constant String := Get_Argument; begin if Model_File'Length = 0 then Usage; Set_Exit_Status (2); return; end if; Gen.Generator.Initialize (Generator); Gen.Generator.Read_Model (Generator, Model_File); Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_PACKAGE, "model"); Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_TABLE, "sql"); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); end; exception when E : XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); end DBMapper;
----------------------------------------------------------------------- -- dbmapper -- Database Mapper Generator -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Sax.Readers; use Sax.Readers; with Ada.Text_IO; with Ada.Exceptions; with Ada.Command_Line; with Gen.Generator; procedure DBMapper is use Ada; use Ada.Command_Line; Generator : Gen.Generator.Handler; Release : constant String := "ADO Generator 0.2, Stephane Carrez"; Copyright : constant String := "Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc."; ----------------- -- Output_File -- ----------------- -------------------------------------------------- -- Usage -------------------------------------------------- procedure Usage is use Ada.Text_IO; begin Put_Line (Release); Put_Line (Copyright); New_Line; Put ("Usage: "); Put (Command_Name); Put_Line (" [-v] [-o directory] [-t templates] model.xml"); Put_Line ("where:"); Put_Line (" -v Verbose"); Put_Line (" -q Query mode"); Put_Line (" -o directory Directory where the Ada mapping files are generated"); Put_Line (" -t templates Directory where the Ada templates are defined"); New_Line; Put_Line (" -h Requests this info."); New_Line; end Usage; begin -- Parse the command line loop case Getopt ("o: t:") is when ASCII.Nul => exit; when 'o' => Gen.Generator.Set_Result_Directory (Generator, Parameter & "/"); when 't' => Gen.Generator.Set_Template_Directory (Generator, Parameter & "/"); when others => null; end case; end loop; Gen.Generator.Initialize (Generator); loop declare Model_File : constant String := Get_Argument; begin exit when Model_File'Length = 0; -- if Model_File'Length = 0 then -- Usage; -- Set_Exit_Status (2); -- return; -- end if; Gen.Generator.Read_Model (Generator, Model_File); end; end loop; Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_PACKAGE, "model"); Gen.Generator.Generate_All (Generator, Gen.Generator.ITERATION_TABLE, "sql"); Ada.Command_Line.Set_Exit_Status (Gen.Generator.Get_Status (Generator)); exception when E : XML_Fatal_Error => Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); end DBMapper;
Allow to read several model files and generate all the necessary packages.
Allow to read several model files and generate all the necessary packages.
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
38961623517db862a67495e389f80a2750c20d56
resources/scripts/archive/archivetoday.ads
resources/scripts/archive/archivetoday.ads
-- Copyright 2017 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. name = "Archive.Today" type = "archive" function start() setratelimit(1) end function vertical(ctx, domain) scrape(ctx, buildurl(domain)) end function buildurl(domain) return "http://archive.is/*." .. domain end
-- Copyright 2017 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. name = "ArchiveToday" type = "archive" function start() setratelimit(1) end function vertical(ctx, domain) scrape(ctx, buildurl(domain)) end function buildurl(domain) return "http://archive.is/*." .. domain end
Rename Archive.Today to ArchiveToday
Rename Archive.Today to ArchiveToday
Ada
apache-2.0
caffix/amass,caffix/amass
57b3dacb5abc5d0b67c3a21392fdb72e6135b841
src/sys/http/util-http-mockups.adb
src/sys/http/util-http-mockups.adb
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Http.Mockups is ----------------- -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Message : in Mockup_Message; Name : in String) return Boolean is begin return Message.Headers.Contains (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. -- ------------------------------ overriding function Get_Header (Message : in Mockup_Message; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Message.Headers.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else return ""; end if; 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 (Message : in out Mockup_Message; Name : in String; Value : in String) is begin Message.Headers.Include (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 (Message : in out Mockup_Message; Name : in String; Value : in String) is Pos : constant Util.Strings.Maps.Cursor := Message.Headers.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then declare Header : constant String := Util.Strings.Maps.Element (Pos); begin Message.Headers.Replace_Element (Pos, Header & ASCII.CR & ASCII.LF & Value); end; else Message.Headers.Include (Name, Value); end if; end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Message : in Mockup_Message; Process : not null access procedure (Name : in String; Value : in String)) is Iter : Util.Strings.Maps.Cursor := Message.Headers.First; begin while Util.Strings.Maps.Has_Element (Iter) loop Util.Strings.Maps.Query_Element (Iter, Process); Util.Strings.Maps.Next (Iter); end loop; end Iterate_Headers; -- ------------- -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Mockup_Response) return String is begin return Util.Strings.Builders.To_Array (Reply.Content); end Get_Body; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Mockup_Response) return Util.Blobs.Blob_Ref is use Ada.Streams; Result : constant Util.Blobs.Blob_Ref := Util.Blobs.Create_Blob (Size => Util.Strings.Builders.Length (Reply.Content)); Offset : Stream_Element_Offset := 1; procedure Append (Content : in String) is C : Stream_Element_Array (1 .. Stream_Element_Offset (Content'Length)); for C'Address use Content'Address; begin Result.Value.Data (Offset .. Offset + C'Length - 1) := C; Offset := Offset + C'Length; end Append; procedure Copy is new Util.Strings.Builders.Inline_Iterate (Append); begin Copy (Reply.Content); return Result; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ overriding function Get_Status (Reply : in Mockup_Response) return Natural is begin return Reply.Status; end Get_Status; -- ------------------------------ -- Set the response status code. -- ------------------------------ procedure Set_Status (Reply : in out Mockup_Response; Status : in Natural) is begin Reply.Status := Status; end Set_Status; -- ------------------------------ -- Set the response body. -- ------------------------------ procedure Set_Body (Reply : in out Mockup_Response; Content : in String) is begin Util.Strings.Builders.Clear (Reply.Content); Util.Strings.Builders.Append (Reply.Content, Content); end Set_Body; -- ------------------------------ -- Append the content to the response body. -- ------------------------------ procedure Append_Body (Reply : in out Mockup_Response; Content : in String) is begin Util.Strings.Builders.Append (Reply.Content, Content); end Append_Body; end Util.Http.Mockups;
----------------------------------------------------------------------- -- util-http-clients-curl -- HTTP Clients with CURL -- Copyright (C) 2012, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Http.Mockups is ----------------- -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Message : in Mockup_Message; Name : in String) return Boolean is begin return Message.Headers.Contains (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. -- ------------------------------ overriding function Get_Header (Message : in Mockup_Message; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Message.Headers.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else return ""; end if; 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 (Message : in out Mockup_Message; Name : in String; Value : in String) is begin Message.Headers.Include (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 (Message : in out Mockup_Message; Name : in String; Value : in String) is Pos : constant Util.Strings.Maps.Cursor := Message.Headers.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then declare Header : constant String := Util.Strings.Maps.Element (Pos); begin Message.Headers.Replace_Element (Pos, Header & ASCII.CR & ASCII.LF & Value); end; else Message.Headers.Include (Name, Value); end if; end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Message : in Mockup_Message; Process : not null access procedure (Name : in String; Value : in String)) is Iter : Util.Strings.Maps.Cursor := Message.Headers.First; begin while Util.Strings.Maps.Has_Element (Iter) loop Util.Strings.Maps.Query_Element (Iter, Process); Util.Strings.Maps.Next (Iter); end loop; end Iterate_Headers; -- ------------- -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Mockup_Response) return String is begin return Util.Strings.Builders.To_Array (Reply.Content); end Get_Body; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Mockup_Response) return Util.Blobs.Blob_Ref is use Ada.Streams; procedure Append (Content : in String); Result : constant Util.Blobs.Blob_Ref := Util.Blobs.Create_Blob (Size => Util.Strings.Builders.Length (Reply.Content)); Offset : Stream_Element_Offset := 1; procedure Append (Content : in String) is C : Stream_Element_Array (1 .. Stream_Element_Offset (Content'Length)); for C'Address use Content'Address; begin Result.Value.Data (Offset .. Offset + C'Length - 1) := C; Offset := Offset + C'Length; end Append; procedure Copy is new Util.Strings.Builders.Inline_Iterate (Append); begin Copy (Reply.Content); return Result; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ overriding function Get_Status (Reply : in Mockup_Response) return Natural is begin return Reply.Status; end Get_Status; -- ------------------------------ -- Set the response status code. -- ------------------------------ procedure Set_Status (Reply : in out Mockup_Response; Status : in Natural) is begin Reply.Status := Status; end Set_Status; -- ------------------------------ -- Set the response body. -- ------------------------------ procedure Set_Body (Reply : in out Mockup_Response; Content : in String) is begin Util.Strings.Builders.Clear (Reply.Content); Util.Strings.Builders.Append (Reply.Content, Content); end Set_Body; -- ------------------------------ -- Append the content to the response body. -- ------------------------------ procedure Append_Body (Reply : in out Mockup_Response; Content : in String) is begin Util.Strings.Builders.Append (Reply.Content, Content); end Append_Body; end Util.Http.Mockups;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6412994ce254842af5f4541ebd59ade4c91e88be
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies (yellow). The framework defines a simple role based security policy and an URL -- security policy intended to provide security in web applications. The security policy manager -- reads some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending -- on the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- -- == Principal == -- A principal is created by using either the [Security_Auth OpenID], -- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces -- an object that must implement the <tt>Principal</tt> interface. For example: -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth); -- -- or -- -- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token -- -- The principal is then stored in a security context. -- -- @include security-contexts.ads -- -- [Security_Policies Security Policies] -- [Security_Auth OpenID] -- [Security_OAuth OAuth] -- package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies (yellow). The framework defines a simple role based security policy and an URL -- security policy intended to provide security in web applications. The security policy manager -- reads some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending -- on the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- -- == Principal == -- A principal is created by using either the [Security_Auth OpenID], -- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces -- an object that must implement the <tt>Principal</tt> interface. For example: -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth); -- -- or -- -- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token -- -- The principal is then stored in a security context. -- -- @include security-contexts.ads -- -- [Security_Policies Security Policies] -- [Security_Auth OpenID] -- [Security_OAuth OAuth] -- package Security is pragma Preelaborate; -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Make the package Preelaborate
Make the package Preelaborate
Ada
apache-2.0
stcarrez/ada-security
bbedce1cbee339cfa2ff1ab62a86f9e6b0383112
src/os-linux/util-streams-raw.adb
src/os-linux/util-streams-raw.adb
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams (OS specific) -- 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.IO_Exceptions; package body Util.Streams.Raw is use Util.Systems.Os; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is begin if Stream.File /= NO_FILE then if Close (Stream.File) /= 0 then raise Ada.IO_Exceptions.Device_Error; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin if Write (Stream.File, Buffer'Address, Buffer'Length) < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : Ssize_T; begin Res := Read (Stream.File, Into'Address, Into'Length); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Reposition the read/write file offset. -- ----------------------- procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) is use type Util.Systems.Types.off_t; Res : Util.Systems.Types.off_t; begin Res := Sys_Lseek (Stream.File, Pos, Mode); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Seek; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams (OS specific) -- Copyright (C) 2011, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Raw is use Util.Systems.Os; use type Util.Systems.Types.File_Type; -- ----------------------- -- Initialize the raw stream to read and write on the given file descriptor. -- ----------------------- procedure Initialize (Stream : in out Raw_Stream; File : in File_Type) is begin if Stream.File /= NO_FILE then raise Ada.IO_Exceptions.Status_Error; end if; Stream.File := File; end Initialize; -- ----------------------- -- Close the stream. -- ----------------------- overriding procedure Close (Stream : in out Raw_Stream) is begin if Stream.File /= NO_FILE then if Close (Stream.File) /= 0 then raise Ada.IO_Exceptions.Device_Error; end if; Stream.File := NO_FILE; end if; end Close; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is begin if Write (Stream.File, Buffer'Address, Buffer'Length) < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Res : Ssize_T; begin Res := Read (Stream.File, Into'Address, Into'Length); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1; end Read; -- ----------------------- -- Reposition the read/write file offset. -- ----------------------- procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) is -- use type Util.Systems.Types.off_t; Res : Util.Systems.Types.off_t; begin Res := Sys_Lseek (Stream.File, Pos, Mode); if Res < 0 then raise Ada.IO_Exceptions.Device_Error; end if; end Seek; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- procedure Finalize (Object : in out Raw_Stream) is begin Close (Object); end Finalize; end Util.Streams.Raw;
Use Util.Systems.Types.File_Type type
Use Util.Systems.Types.File_Type type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bcc012c6e83ecebd24b6e06337609d049ac40259
regtests/ado-objects-tests.adb
regtests/ado-objects-tests.adb
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Sessions; with Regtests.Simple.Model; with Regtests.Comments; with Regtests.Statements.Model; package body ADO.Objects.Tests is use Util.Tests; use type Ada.Containers.Hash_Type; -- Test the Set_xxx and Get_xxx operation on various simple times. generic Name : String; type Element_Type (<>) is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; with procedure Set_Value (Item : in out Regtests.Statements.Model.Nullable_Table_Ref; Val : in Element_Type); with function Get_Value (Item : in Regtests.Statements.Model.Nullable_Table_Ref) return Element_Type; Val1 : Element_Type; Val2 : Element_Type; procedure Test_Op (T : in out Test); procedure Test_Op (T : in out Test) is Item1 : Regtests.Statements.Model.Nullable_Table_Ref; Item2 : Regtests.Statements.Model.Nullable_Table_Ref; Item3 : Regtests.Statements.Model.Nullable_Table_Ref; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin Set_Value (Item1, Val1); Item1.Save (DB); T.Assert (Item1.Is_Inserted, Name & " item is created"); -- Util.Tests.Assert_Equals (T, T'Image (Val), T'Image ( -- Load in a second item and check the value. Item2.Load (DB, Item1.Get_Id); T.Assert (Item2.Get_Id = Item1.Get_Id, Name & " item2 cannot be loaded"); -- T.Assert (Get_Value (Item2) = Val1, Name & " invalid value loaded in item2"); -- Change the item in database. Set_Value (Item2, Val2); Item2.Save (DB); T.Assert (Get_Value (Item2) = Val2, Name & " invalid value loaded in item2"); -- Load again and compare to check the update. Item3.Load (DB, Item2.Get_Id); T.Assert (Get_Value (Item3) = Val2, Name & " invalid value loaded in item3"); end Test_Op; procedure Test_Object_Nullable_Integer is new Test_Op ("Nullable_Integer", Nullable_Integer, "=", Regtests.Statements.Model.Set_Int_Value, Regtests.Statements.Model.Get_Int_Value, Nullable_Integer '(Value => 123, Is_Null => False), Nullable_Integer '(Value => 0, Is_Null => True)); procedure Test_Object_Nullable_Entity_Type is new Test_Op ("Nullable_Entity_Type", Nullable_Entity_Type, "=", Regtests.Statements.Model.Set_Entity_Value, Regtests.Statements.Model.Get_Entity_Value, Nullable_Entity_Type '(Value => 456, Is_Null => False), Nullable_Entity_Type '(Value => 0, Is_Null => True)); procedure Test_Object_Nullable_Time is new Test_Op ("Nullable_Time", Nullable_Time, "=", Regtests.Statements.Model.Set_Time_Value, Regtests.Statements.Model.Get_Time_Value, Nullable_Time '(Value => 456, Is_Null => False), Nullable_Time '(Value => <>, Is_Null => True)); function Get_Allocate_Key (N : Identifier) return Object_Key; function Get_Allocate_Key (N : Identifier) return Object_Key is Result : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); begin Set_Value (Result, N); return Result; end Get_Allocate_Key; -- ------------------------------ -- Various tests on Hash and key comparison -- ------------------------------ procedure Test_Key (T : in out Test) is K1 : constant Object_Key := Get_Allocate_Key (1); K2 : Object_Key (Of_Type => KEY_STRING, Of_Class => Regtests.Simple.Model.USER_TABLE); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE); begin T.Assert (not (K1 = K2), "Key on different tables must be different"); T.Assert (not (K2 = K4), "Key with different type must be different"); T.Assert (K1 = K3, "Keys are identical"); T.Assert (Equivalent_Elements (K1, K3), "Keys are identical"); T.Assert (Equivalent_Elements (K3, K1), "Keys are identical"); T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical"); Set_Value (K3, 2); T.Assert (not (K1 = K3), "Keys should be different"); T.Assert (Hash (K1) /= Hash (K3), "Hash should be different"); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); Set_Value (K4, 1); T.Assert (Hash (K1) /= Hash (K4), "Hash on key with same value and different tables should be different"); T.Assert (not (K4 = K1), "Key on different tables should be different"); Set_Value (K2, 1); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); end Test_Key; -- ------------------------------ -- Check: -- Object_Ref := (reference counting) -- Object_Ref.Copy -- Object_Ref.Get_xxx generated method -- Object_Ref.Set_xxx generated method -- Object_Ref.= -- ------------------------------ procedure Test_Object_Ref (T : in out Test) is use type Regtests.Simple.Model.User_Ref; Obj1 : Regtests.Simple.Model.User_Ref; Null_Obj : Regtests.Simple.Model.User_Ref; begin T.Assert (Obj1 = Null_Obj, "Two null objects are identical"); for I in 1 .. 10 loop Obj1.Set_Name ("User name"); T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result"); T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object"); declare Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1; Obj3 : Regtests.Simple.Model.User_Ref; begin Obj1.Copy (Obj3); Obj3.Set_Id (2); -- Check the copy T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy"); -- Change original, make sure it's the same of Obj2. Obj1.Set_Name ("Second name"); T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); -- The copy is not modified T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); end; end loop; end Test_Object_Ref; -- ------------------------------ -- Test creation of an object with lazy loading. -- ------------------------------ procedure Test_Create_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; Cmt : Regtests.Comments.Comment_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (not U2.Get_Name.Is_Null, "Cannot load created object"); Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name.Value), "Cannot load created object"); Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load"); T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load"); end; -- Create a comment for the user. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe")); Cmt.Set_User (User); Cmt.Set_Entity_Id (2); Cmt.Set_Entity_Type (1); -- Cmt.Set_Date (ADO.DEFAULT_TIME); Cmt.Set_Date (Ada.Calendar.Clock); Cmt.Save (S); S.Commit; end; -- Load that comment. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; C2 : Regtests.Comments.Comment_Ref; begin T.Assert (not C2.Is_Loaded, "Object is not loaded"); C2.Load (S, Cmt.Get_Id); T.Assert (not C2.Is_Null, "Loading of object failed"); T.Assert (C2.Is_Loaded, "Object is loaded"); T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load"); T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message), "Invalid message"); T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null"); -- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set"); -- Check that we can access the user name (lazy load) Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name.Value), "Cannot load created object"); end; end Test_Create_Object; -- ------------------------------ -- Test creation and deletion of an object record -- ------------------------------ procedure Test_Delete_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe (delete)"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it and delete it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); S.Begin_Transaction; U2.Delete (S); S.Commit; end; -- Try to load the deleted object. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (False, "Load of a deleted object should raise NOT_FOUND"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Object; -- ------------------------------ -- Test Is_Inserted and Is_Null -- ------------------------------ procedure Test_Is_Inserted (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED"); T.Assert (User.Is_Null, "A null object should be marked as NULL"); -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("John"); T.Assert (not User.Is_Null, "User should not be NULL"); T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database"); User.Set_Value (1); User.Save (S); S.Commit; T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED"); T.Assert (not User.Is_Null, "User should not be NULL"); end; declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; John : Regtests.Simple.Model.User_Ref; begin John.Load (S, User.Get_Id); T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED"); T.Assert (not John.Is_Null, "After a load, the object should not be NULL"); end; end Test_Is_Inserted; package Caller is new Util.Test_Caller (Test, "ADO.Objects"); -- ------------------------------ -- Add the tests in the test suite -- ------------------------------ procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access); Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Integer)", Test_Object_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Entity_Type)", Test_Object_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Time)", Test_Object_Nullable_Time'Access); end Add_Tests; end ADO.Objects.Tests;
----------------------------------------------------------------------- -- ADO Objects Tests -- Tests for ADO.Objects -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ADO.Sessions; with Regtests.Simple.Model; with Regtests.Comments; with Regtests.Statements.Model; package body ADO.Objects.Tests is use Util.Tests; use type Ada.Containers.Hash_Type; -- Test the Set_xxx and Get_xxx operation on various simple times. generic Name : String; type Element_Type (<>) is private; with function "=" (Left, Right : in Element_Type) return Boolean is <>; with procedure Set_Value (Item : in out Regtests.Statements.Model.Nullable_Table_Ref; Val : in Element_Type); with function Get_Value (Item : in Regtests.Statements.Model.Nullable_Table_Ref) return Element_Type; Val1 : Element_Type; Val2 : Element_Type; Val3 : Element_Type; procedure Test_Op (T : in out Test); procedure Test_Op (T : in out Test) is Item1 : Regtests.Statements.Model.Nullable_Table_Ref; Item2 : Regtests.Statements.Model.Nullable_Table_Ref; Item3 : Regtests.Statements.Model.Nullable_Table_Ref; DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin Set_Value (Item1, Val1); Item1.Save (DB); T.Assert (Item1.Is_Inserted, Name & " item is created"); -- Util.Tests.Assert_Equals (T, T'Image (Val), T'Image ( -- Load in a second item and check the value. Item2.Load (DB, Item1.Get_Id); T.Assert (Item2.Get_Id = Item1.Get_Id, Name & " item2 cannot be loaded"); -- T.Assert (Get_Value (Item2) = Val1, Name & " invalid value loaded in item2"); -- Change the item in database. Set_Value (Item2, Val2); Item2.Save (DB); T.Assert (Get_Value (Item2) = Val2, Name & " invalid value loaded in item2"); -- Load again and compare to check the update. Item3.Load (DB, Item2.Get_Id); T.Assert (Get_Value (Item3) = Val2, Name & " invalid value loaded in item3"); begin Set_Value (Item1, Val3); Item1.Save (DB); T.Fail ("No LAZY_LOCK exception was raised."); exception when ADO.Objects.LAZY_LOCK => null; end; Set_Value (Item3, Val3); Item3.Save (DB); T.Assert (Get_Value (Item3) = Val3, Name & " invalid value loaded in item3"); Item1.Load (DB, Item1.Get_Id); T.Assert (Get_Value (Item1) = Val3, Name & " invalid value loaded in item3"); end Test_Op; procedure Test_Object_Nullable_Integer is new Test_Op ("Nullable_Integer", Nullable_Integer, "=", Regtests.Statements.Model.Set_Int_Value, Regtests.Statements.Model.Get_Int_Value, Nullable_Integer '(Value => 123, Is_Null => False), Nullable_Integer '(Value => 0, Is_Null => True), Nullable_Integer '(Value => 231, Is_Null => False)); procedure Test_Object_Nullable_Entity_Type is new Test_Op ("Nullable_Entity_Type", Nullable_Entity_Type, "=", Regtests.Statements.Model.Set_Entity_Value, Regtests.Statements.Model.Get_Entity_Value, Nullable_Entity_Type '(Value => 456, Is_Null => False), Nullable_Entity_Type '(Value => 0, Is_Null => True), Nullable_Entity_Type '(Value => 564, Is_Null => False)); procedure Test_Object_Nullable_Time is new Test_Op ("Nullable_Time", Nullable_Time, "=", Regtests.Statements.Model.Set_Time_Value, Regtests.Statements.Model.Get_Time_Value, Nullable_Time '(Value => 45621, Is_Null => False), Nullable_Time '(Value => <>, Is_Null => True), Nullable_Time '(Value => 56412, Is_Null => False)); function Get_Allocate_Key (N : Identifier) return Object_Key; function Get_Allocate_Key (N : Identifier) return Object_Key is Result : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE); begin Set_Value (Result, N); return Result; end Get_Allocate_Key; -- ------------------------------ -- Various tests on Hash and key comparison -- ------------------------------ procedure Test_Key (T : in out Test) is K1 : constant Object_Key := Get_Allocate_Key (1); K2 : Object_Key (Of_Type => KEY_STRING, Of_Class => Regtests.Simple.Model.USER_TABLE); K3 : Object_Key := K1; K4 : Object_Key (Of_Type => KEY_INTEGER, Of_Class => Regtests.Simple.Model.USER_TABLE); begin T.Assert (not (K1 = K2), "Key on different tables must be different"); T.Assert (not (K2 = K4), "Key with different type must be different"); T.Assert (K1 = K3, "Keys are identical"); T.Assert (Equivalent_Elements (K1, K3), "Keys are identical"); T.Assert (Equivalent_Elements (K3, K1), "Keys are identical"); T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical"); Set_Value (K3, 2); T.Assert (not (K1 = K3), "Keys should be different"); T.Assert (Hash (K1) /= Hash (K3), "Hash should be different"); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); Set_Value (K4, 1); T.Assert (Hash (K1) /= Hash (K4), "Hash on key with same value and different tables should be different"); T.Assert (not (K4 = K1), "Key on different tables should be different"); Set_Value (K2, 1); T.Assert (Hash (K1) /= Hash (K2), "Hash should be different"); end Test_Key; -- ------------------------------ -- Check: -- Object_Ref := (reference counting) -- Object_Ref.Copy -- Object_Ref.Get_xxx generated method -- Object_Ref.Set_xxx generated method -- Object_Ref.= -- ------------------------------ procedure Test_Object_Ref (T : in out Test) is use type Regtests.Simple.Model.User_Ref; Obj1 : Regtests.Simple.Model.User_Ref; Null_Obj : Regtests.Simple.Model.User_Ref; begin T.Assert (Obj1 = Null_Obj, "Two null objects are identical"); for I in 1 .. 10 loop Obj1.Set_Name ("User name"); T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result"); T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object"); declare Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1; Obj3 : Regtests.Simple.Model.User_Ref; begin Obj1.Copy (Obj3); Obj3.Set_Id (2); -- Check the copy T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy"); -- Change original, make sure it's the same of Obj2. Obj1.Set_Name ("Second name"); T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy"); T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment"); -- The copy is not modified T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy"); end; end loop; end Test_Object_Ref; -- ------------------------------ -- Test creation of an object with lazy loading. -- ------------------------------ procedure Test_Create_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; Cmt : Regtests.Comments.Comment_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (not U2.Get_Name.Is_Null, "Cannot load created object"); Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name.Value), "Cannot load created object"); Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load"); T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load"); end; -- Create a comment for the user. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe")); Cmt.Set_User (User); Cmt.Set_Entity_Id (2); Cmt.Set_Entity_Type (1); -- Cmt.Set_Date (ADO.DEFAULT_TIME); Cmt.Set_Date (Ada.Calendar.Clock); Cmt.Save (S); S.Commit; end; -- Load that comment. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; C2 : Regtests.Comments.Comment_Ref; begin T.Assert (not C2.Is_Loaded, "Object is not loaded"); C2.Load (S, Cmt.Get_Id); T.Assert (not C2.Is_Null, "Loading of object failed"); T.Assert (C2.Is_Loaded, "Object is loaded"); T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load"); T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message), "Invalid message"); T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null"); -- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set"); -- Check that we can access the user name (lazy load) Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name.Value), "Cannot load created object"); end; end Test_Create_Object; -- ------------------------------ -- Test creation and deletion of an object record -- ------------------------------ procedure Test_Delete_Object (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("Joe (delete)"); User.Set_Value (0); User.Save (S); S.Commit; end; -- Load it and delete it from another session. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); S.Begin_Transaction; U2.Delete (S); S.Commit; end; -- Try to load the deleted object. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; U2 : Regtests.Simple.Model.User_Ref; begin U2.Load (S, User.Get_Id); T.Assert (False, "Load of a deleted object should raise NOT_FOUND"); exception when ADO.Objects.NOT_FOUND => null; end; end Test_Delete_Object; -- ------------------------------ -- Test Is_Inserted and Is_Null -- ------------------------------ procedure Test_Is_Inserted (T : in out Test) is User : Regtests.Simple.Model.User_Ref; begin T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED"); T.Assert (User.Is_Null, "A null object should be marked as NULL"); -- Create an object within a transaction. declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin S.Begin_Transaction; User.Set_Name ("John"); T.Assert (not User.Is_Null, "User should not be NULL"); T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database"); User.Set_Value (1); User.Save (S); S.Commit; T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED"); T.Assert (not User.Is_Null, "User should not be NULL"); end; declare S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; John : Regtests.Simple.Model.User_Ref; begin John.Load (S, User.Get_Id); T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED"); T.Assert (not John.Is_Null, "After a load, the object should not be NULL"); end; end Test_Is_Inserted; package Caller is new Util.Test_Caller (Test, "ADO.Objects"); -- ------------------------------ -- Add the tests in the test suite -- ------------------------------ procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access); Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access); Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Integer)", Test_Object_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Entity_Type)", Test_Object_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Objects (Nullable_Time)", Test_Object_Nullable_Time'Access); end Add_Tests; end ADO.Objects.Tests;
Update Test_Op generic test to verify optimistic locking
Update Test_Op generic test to verify optimistic locking
Ada
apache-2.0
stcarrez/ada-ado
58621b0bda4748cb11b746d7c9e4f0b6d1f8aded
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Services.Contexts; with AWA.Questions.Modules; with AWA.Questions.Beans; with AWA.Tests.Helpers.Users; package body AWA.Questions.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list", Test_List_Questions'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Manager; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I append strings in Ada?"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do?"); T.Manager.Save_Question (Q); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do? " & "This is a stupid question for someone who reads this file. " & "But I need some long text for the unit test."); T.Manager.Save_Question (Q); end Test_Create_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use AWA.Questions.Models; use type Util.Beans.Basic.Readonly_Bean_Access; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; Module : AWA.Questions.Modules.Question_Module_Access; List : Util.Beans.Basic.Readonly_Bean_Access; Bean : Util.Beans.Objects.Object; Count : Natural; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Module := AWA.Questions.Modules.Get_Question_Module; List := AWA.Questions.Beans.Create_Question_List_Bean (Module); T.Assert (List /= null, "The Create_Question_List_Bean returned null"); Bean := Util.Beans.Objects.To_Object (List); T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null"); Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count; T.Assert (Count > 0, "The list of question is empty"); end Test_List_Questions; end AWA.Questions.Services.Tests;
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with ASF.Contexts.Faces; with ASF.Contexts.Faces.Mockup; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Questions.Modules; with AWA.Questions.Beans; with AWA.Votes.Beans; with AWA.Tests.Helpers.Users; package body AWA.Questions.Services.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Questions.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list", Test_List_Questions'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean", Test_Question_Vote'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans questionVote bean (anonymous user)", Test_Question_Vote'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Q : AWA.Questions.Models.Question_Ref; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Questions.Modules.Get_Question_Manager; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I append strings in Ada?"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do?"); T.Manager.Save_Question (Q); Q.Set_Description ("I have two strings that I want to concatenate. + does not work. " & "I also tried '.' without success. What should I do? " & "This is a stupid question for someone who reads this file. " & "But I need some long text for the unit test."); T.Manager.Save_Question (Q); end Test_Create_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use AWA.Questions.Models; use type Util.Beans.Basic.Readonly_Bean_Access; Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Module : AWA.Questions.Modules.Question_Module_Access; List : Util.Beans.Basic.Readonly_Bean_Access; Bean : Util.Beans.Objects.Object; Count : Natural; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Module := AWA.Questions.Modules.Get_Question_Module; List := AWA.Questions.Beans.Create_Question_List_Bean (Module); T.Assert (List /= null, "The Create_Question_List_Bean returned null"); Bean := Util.Beans.Objects.To_Object (List); T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null"); Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count; T.Assert (Count > 0, "The list of question is empty"); end Test_List_Questions; -- ------------------------------ -- Do a vote on a question through the question vote bean. -- ------------------------------ procedure Do_Vote (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Context : ASF.Contexts.Faces.Mockup.Mockup_Faces_Context; Outcome : Ada.Strings.Unbounded.Unbounded_String; Bean : Util.Beans.Basic.Readonly_Bean_Access; Vote : AWA.Votes.Beans.Vote_Bean_Access; begin Bean := Context.Get_Bean ("questionVote"); T.Assert (Bean /= null, "The questionVote bean was not created"); T.Assert (Bean.all in AWA.Votes.Beans.Vote_Bean'Class, "The questionVote is not a Vote_Bean"); Vote := AWA.Votes.Beans.Vote_Bean (Bean.all)'Access; Vote.Rating := 1; Vote.Entity_Id := 1; Vote.Vote_Up (Outcome); end Do_Vote; -- ------------------------------ -- Test anonymous user voting for a question. -- ------------------------------ procedure Test_Question_Vote_Anonymous (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx); Do_Vote (T); T.Fail ("Anonymous users should not be allowed to vote"); exception when AWA.Permissions.NO_PERMISSION => null; end Test_Question_Vote_Anonymous; -- ------------------------------ -- Test voting for a question. -- ------------------------------ procedure Test_Question_Vote (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Do_Vote (T); end Test_Question_Vote; end AWA.Questions.Services.Tests;
Add unit tests for the questionVote bean
Add unit tests for the questionVote bean
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
67e0ebd6335f6c5763735bd0d0df9cf04480939c
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies. The framework defines a simple role based security policy and an URL security -- policy intended to provide security in web applications. The security policy manager reads -- some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components (yellow) are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance. Additional security policy context can be added depending on -- the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies. The framework defines a simple role based security policy and an URL security -- policy intended to provide security in web applications. The security policy manager reads -- some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components (yellow) are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance. Additional security policy context can be added depending on -- the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Make the OAuth and OpenID a separate wiki page
Make the OAuth and OpenID a separate wiki page
Ada
apache-2.0
stcarrez/ada-security
21313f559f3849569ef85a502e4c8e0d7290cf6d
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 Ada.Strings.Unbounded; with Ada.Directories; with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Exceptions; with Ada.Streams.Stream_IO; with Util.Log.Loggers; with Util.Files; with Interfaces.C; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- 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 Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin 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; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- 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; 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; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); -- ------------------------------ -- 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 Result : constant File_Type := new File '(Len => Name'Length, Id => NO_IDENTIFIER, Dir => Dir, Name => Name, others => <>); begin 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; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- 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; end Babel.Files;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/babel
8f042c31e602d217e141f574aa07366289be2613
src/gen-model-enums.adb
src/gen-model-enums.adb
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- package body Gen.Model.Enums is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Value_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "value" then return Util.Beans.Objects.To_Object (From.Number); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Enum_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "values" then return From.Values_Bean; elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (True); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); else return Mappings.Mapping_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Compare two enum literals. -- ------------------------------ function "<" (Left, Right : in Value_Definition_Access) return Boolean is begin return Left.Number < Right.Number; end "<"; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is procedure Sort is new Value_List.Sort_On ("<"); begin O.Target := O.Type_Name; Sort (O.Values); end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Enum_Definition) is begin O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an enum value to this enum definition and return the new value. -- ------------------------------ procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access) is begin Value := new Value_Definition; Value.Set_Name (Name); Value.Number := Enum.Values.Get_Count; Enum.Values.Append (Value); end Add_Value; -- ------------------------------ -- Create an enum with the given name. -- ------------------------------ function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is Enum : constant Enum_Definition_Access := new Enum_Definition; begin Enum.Set_Name (Name); declare Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1); Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name)); else Enum.Pkg_Name := To_Unbounded_String ("ADO"); Enum.Type_Name := Enum.Name; end if; end; return Enum; end Create_Enum; end Gen.Model.Enums;
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- Copyright (C) 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.Enums is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Value_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "value" then return Util.Beans.Objects.To_Object (From.Number); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Enum_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "values" then return From.Values_Bean; elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (True); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (Mappings.Get_Type_Name (From.Sql_Type)); else return Mappings.Mapping_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Compare two enum literals. -- ------------------------------ function "<" (Left, Right : in Value_Definition_Access) return Boolean is begin return Left.Number < Right.Number; end "<"; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is procedure Sort is new Value_List.Sort_On ("<"); begin O.Target := O.Type_Name; Sort (O.Values); end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Enum_Definition) is begin O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an enum value to this enum definition and return the new value. -- ------------------------------ procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access) is begin Value := new Value_Definition; Value.Set_Name (Name); Value.Number := Enum.Values.Get_Count; Enum.Values.Append (Value); end Add_Value; -- ------------------------------ -- Create an enum with the given name. -- ------------------------------ function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is Enum : constant Enum_Definition_Access := new Enum_Definition; begin Enum.Set_Name (Name); declare Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1); Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name)); else Enum.Pkg_Name := To_Unbounded_String ("ADO"); Enum.Type_Name := Enum.Name; end if; end; return Enum; end Create_Enum; end Gen.Model.Enums;
Use the Get_Type_Mapping function to convert the Sql_Type into a target SQL type (the SQL type can be different for Postgresql/MySQL/SQLite)
Use the Get_Type_Mapping function to convert the Sql_Type into a target SQL type (the SQL type can be different for Postgresql/MySQL/SQLite)
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
4fc54093ff6ef292001e29fb75f66d7c42f52adf
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Get the driver index that corresponds to the driver for this database connection string. -- ------------------------------ function Get_Driver (Config : in Configuration) return Driver_Index is Driver : constant Driver_Access := Get_Driver (Config.Get_Driver); begin if Driver = null then return Driver_Index'First; else return Driver.Get_Driver_Index; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Driver : Driver_Access; Log_URI : constant String := Config.Get_Log_URI; begin Driver := Get_Driver (Config.Get_Driver); if Driver = null then Log.Error ("No driver found for connection {0}", Log_URI); raise ADO.Configs.Connection_Error with "Data source is not initialized: driver '" & Config.Get_Driver & "' not found"; end if; Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Log_URI); raise; end Create_Connection; -- ------------------------------ -- Get the database driver index. -- ------------------------------ function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database_Connection'Class (Database).Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; Dynamic_Load : constant String := Get_Config (ADO.Configs.DYNAMIC_DRIVER_LOAD); begin if Dynamic_Load /= "1" and Dynamic_Load /= "true" then Log.Warn ("Dynamic loading of driver '{0}' is disabled", Name); return; end if; Log.Debug ("Loading driver '{0}' from {1}", Name, Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Log.Info ("Initialising driver {0}", Lib); Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Debug ("Get driver {0}", Name); if Name'Length = 0 then return null; end if; for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 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 Util.Systems.DLLs; with System; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Get the driver index that corresponds to the driver for this database connection string. -- ------------------------------ function Get_Driver (Config : in Configuration) return Driver_Index is Driver : constant Driver_Access := Get_Driver (Config.Get_Driver); begin if Driver = null then return Driver_Index'First; else return Driver.Get_Driver_Index; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Driver : Driver_Access; Log_URI : constant String := Config.Get_Log_URI; begin Driver := Get_Driver (Config.Get_Driver); if Driver = null then Log.Error ("No driver found for connection {0}", Log_URI); raise ADO.Configs.Connection_Error with "Data source is not initialized: driver '" & Config.Get_Driver & "' not found"; end if; Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Log_URI); raise; end Create_Connection; -- ------------------------------ -- Get the database driver index. -- ------------------------------ function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database_Connection'Class (Database).Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin if Is_On (ADO.Configs.DYNAMIC_DRIVER_LOAD) then Log.Warn ("Dynamic loading of driver '{0}' is disabled", Name); return; end if; Log.Debug ("Loading driver '{0}' from {1}", Name, Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Log.Info ("Initialising driver {0}", Lib); Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Debug ("Get driver {0}", Name); if Name'Length = 0 then return null; end if; for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Use the Is_On function to check if we can use dynamic load
Use the Is_On function to check if we can use dynamic load
Ada
apache-2.0
stcarrez/ada-ado
17901d851b5efa980a6f14ee52940f5b9b596b65
awa/plugins/awa-counters/src/awa-counters-modules.ads
awa/plugins/awa-counters/src/awa-counters-modules.ads
----------------------------------------------------------------------- -- awa-counters-modules -- Module counters -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Calendar; with ASF.Applications; with AWA.Modules; package AWA.Counters.Modules is -- The name under which the module is registered. NAME : constant String := "counters"; -- Default age limit to flush counters: 5 minutes. DEFAULT_AGE_LIMIT : constant Duration := 5 * 60.0; -- Default maximum number of different counters to keep before flushing. DEFAULT_COUNTER_LIMIT : constant Natural := 1_000; PARAM_AGE_LIMIT : constant String := "counter_age_limit"; PARAM_COUNTER_LIMIT : constant String := "counter_limit"; -- ------------------------------ -- Module counters -- ------------------------------ type Counter_Module is new AWA.Modules.Module with private; type Counter_Module_Access is access all Counter_Module'Class; -- Initialize the counters module. overriding procedure Initialize (Plugin : in out Counter_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 Counter_Module; Props : in ASF.Applications.Config); -- Get the counters module. function Get_Counter_Module return Counter_Module_Access; -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Object</tt>. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class); -- Increment the counter identified by <tt>Counter</tt>. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type); -- Get the current counter value. procedure Get_Counter (Plugin : in out Counter_Module; Counter : in AWA.Counters.Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class; Result : out Natural); -- Flush the existing counters and update all the database records refered to them. procedure Flush (Plugin : in out Counter_Module); private type Definition_Array_Type is array (Counter_Index_Type range <>) of Natural; type Definition_Array_Type_Access is access all Definition_Array_Type; -- The counter map tracks a counter associated with a database object. -- All the database objects refer to the same counter. package Counter_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => ADO.Objects.Object_Key, Element_Type => Positive, Hash => ADO.Objects.Hash, Equivalent_Keys => ADO.Objects."="); -- The <tt>Counter_Map_Array</tt> associate a counter map to each counter definition. type Counter_Map_Array is array (Counter_Index_Type range <>) of Counter_Maps.Map; type Counter_Map_Array_Access is access all Counter_Map_Array; -- Counters are kept temporarily in the <tt>Counter_Table</tt> protected type to avoid -- having to update the database each time a counter is incremented. Counters are flushed -- when the table reaches some limit, or, when the table is oldest than some limit. -- Counters are associated with a day so that it becomes possible to gather per-day counters. -- -- The <tt>Flush</tt> operation on the <tt>Counter_Module</tt> can be used to flush -- the pending counters. For each counter that was updated, it either inserts or -- updates a row in the counters database table. Because such operation is slow, it is not -- implemented in the protected type. Instead, we steal the counter table and replace it -- with a new/empty table. This is done by <tt>Steal_Counters</tt> protected operation. -- While doing the flush, other tasks can increment counters without being blocked by the -- <tt>Flush</tt> operation. protected type Counter_Table is -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Key</tt>. procedure Increment (Counter : in Counter_Index_Type; Key : in ADO.Objects.Object_Key); -- Get the counters that have been collected with the date and prepare to collect -- new counters. procedure Steal_Counters (Result : out Counter_Map_Array_Access; Date : out Ada.Calendar.Time); -- Check if we must flush the counters. function Need_Flush (Limit : in Natural; Seconds : in Duration) return Boolean; -- Get the definition ID associated with the counter. procedure Get_Definition (Counter : in Counter_Index_Type; Result : out Natural); private Day : Ada.Calendar.Time; Day_End : Ada.Calendar.Time; Counters : Counter_Map_Array_Access; Definitions : Definition_Array_Type_Access; Nb_Counters : Natural := 0; end Counter_Table; type Counter_Module is new AWA.Modules.Module with record Counters : Counter_Table; Counter_Limit : Natural := DEFAULT_COUNTER_LIMIT; Age_Limit : Duration := DEFAULT_AGE_LIMIT; end record; end AWA.Counters.Modules;
----------------------------------------------------------------------- -- awa-counters-modules -- Module counters -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Calendar; with ASF.Applications; with AWA.Modules; package AWA.Counters.Modules is -- The name under which the module is registered. NAME : constant String := "counters"; -- Default age limit to flush counters: 5 minutes. DEFAULT_AGE_LIMIT : constant Duration := 5 * 60.0; -- Default maximum number of different counters to keep before flushing. DEFAULT_COUNTER_LIMIT : constant Natural := 1_000; PARAM_AGE_LIMIT : constant String := "counter_age_limit"; PARAM_COUNTER_LIMIT : constant String := "counter_limit"; -- ------------------------------ -- Module counters -- ------------------------------ type Counter_Module is new AWA.Modules.Module with private; type Counter_Module_Access is access all Counter_Module'Class; -- Initialize the counters module. overriding procedure Initialize (Plugin : in out Counter_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 Counter_Module; Props : in ASF.Applications.Config); -- Get the counters module. function Get_Counter_Module return Counter_Module_Access; -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Object</tt>. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class); -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object key <tt>Key</tt>. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type; Key : in ADO.Objects.Object_Key); -- Increment the counter identified by <tt>Counter</tt>. procedure Increment (Plugin : in out Counter_Module; Counter : in Counter_Index_Type); -- Get the current counter value. procedure Get_Counter (Plugin : in out Counter_Module; Counter : in AWA.Counters.Counter_Index_Type; Object : in ADO.Objects.Object_Ref'Class; Result : out Natural); -- Flush the existing counters and update all the database records refered to them. procedure Flush (Plugin : in out Counter_Module); private type Definition_Array_Type is array (Counter_Index_Type range <>) of Natural; type Definition_Array_Type_Access is access all Definition_Array_Type; -- The counter map tracks a counter associated with a database object. -- All the database objects refer to the same counter. package Counter_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => ADO.Objects.Object_Key, Element_Type => Positive, Hash => ADO.Objects.Hash, Equivalent_Keys => ADO.Objects."="); -- The <tt>Counter_Map_Array</tt> associate a counter map to each counter definition. type Counter_Map_Array is array (Counter_Index_Type range <>) of Counter_Maps.Map; type Counter_Map_Array_Access is access all Counter_Map_Array; -- Counters are kept temporarily in the <tt>Counter_Table</tt> protected type to avoid -- having to update the database each time a counter is incremented. Counters are flushed -- when the table reaches some limit, or, when the table is oldest than some limit. -- Counters are associated with a day so that it becomes possible to gather per-day counters. -- -- The <tt>Flush</tt> operation on the <tt>Counter_Module</tt> can be used to flush -- the pending counters. For each counter that was updated, it either inserts or -- updates a row in the counters database table. Because such operation is slow, it is not -- implemented in the protected type. Instead, we steal the counter table and replace it -- with a new/empty table. This is done by <tt>Steal_Counters</tt> protected operation. -- While doing the flush, other tasks can increment counters without being blocked by the -- <tt>Flush</tt> operation. protected type Counter_Table is -- Increment the counter identified by <tt>Counter</tt> and associated with the -- database object <tt>Key</tt>. procedure Increment (Counter : in Counter_Index_Type; Key : in ADO.Objects.Object_Key); -- Get the counters that have been collected with the date and prepare to collect -- new counters. procedure Steal_Counters (Result : out Counter_Map_Array_Access; Date : out Ada.Calendar.Time); -- Check if we must flush the counters. function Need_Flush (Limit : in Natural; Seconds : in Duration) return Boolean; -- Get the definition ID associated with the counter. procedure Get_Definition (Counter : in Counter_Index_Type; Result : out Natural); private Day : Ada.Calendar.Time; Day_End : Ada.Calendar.Time; Counters : Counter_Map_Array_Access; Definitions : Definition_Array_Type_Access; Nb_Counters : Natural := 0; end Counter_Table; type Counter_Module is new AWA.Modules.Module with record Counters : Counter_Table; Counter_Limit : Natural := DEFAULT_COUNTER_LIMIT; Age_Limit : Duration := DEFAULT_AGE_LIMIT; end record; end AWA.Counters.Modules;
Declare the Increment procedure with Object_Key type
Declare the Increment procedure with Object_Key type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c932d8223e67d4fce76d7dc14e503a2cd950eae9
src/util-properties.ads
src/util-properties.ads
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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.Unbounded; with Ada.Finalization; with Ada.Text_IO; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Ada.Strings.Unbounded.Unbounded_String; function "+" (S : String) return Value renames To_Unbounded_String; function "-" (S : Value) return String renames To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled with private; type Manager_Access is access Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Value) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Insert the specified property in the list. procedure Insert (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Value); type Name_Array is array (Natural range <>) of Value; -- Return the name of the properties defined in the manager. function Get_Names (Self : in Manager) return Name_Array; -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type); -- Load the properties from the file. The file must follow the -- definition of Java property files. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract tagged limited record Count : Natural := 0; end record; type Manager_Access is access all Manager'Class; type Manager_Factory is access function return Manager_Access; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean is abstract; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value is abstract; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is abstract; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager; Name : in Value; Item : in Value) is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; procedure Delete (Self : in Manager; Obj : in out Manager_Access) is abstract; function Get_Names (Self : in Manager) return Name_Array is abstract; end Interface_P; procedure Set_Property_Implementation (Self : in out Manager; Impl : in Interface_P.Manager_Access); -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled with record Impl : Interface_P.Manager_Access := null; end record; procedure Adjust (Object : in out Manager); procedure Finalize (Object : in out Manager); end Util.Properties;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 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.Unbounded; with Ada.Finalization; with Ada.Text_IO; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Ada.Strings.Unbounded.Unbounded_String; function "+" (S : String) return Value renames To_Unbounded_String; function "-" (S : Value) return String renames To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled with private; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Value) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Insert the specified property in the list. procedure Insert (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Value); type Name_Array is array (Natural range <>) of Value; -- Return the name of the properties defined in the manager. function Get_Names (Self : in Manager) return Name_Array; -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type); -- Load the properties from the file. The file must follow the -- definition of Java property files. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract tagged limited record Count : Natural := 0; end record; type Manager_Access is access all Manager'Class; type Manager_Factory is access function return Manager_Access; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in Value) return Boolean is abstract; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager; Name : in Value) return Value is abstract; procedure Insert (Self : in out Manager; Name : in Value; Item : in Value) is abstract; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager; Name : in Value; Item : in Value) is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in Value) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; procedure Delete (Self : in Manager; Obj : in out Manager_Access) is abstract; function Get_Names (Self : in Manager) return Name_Array is abstract; end Interface_P; procedure Set_Property_Implementation (Self : in out Manager; Impl : in Interface_P.Manager_Access); -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled with record Impl : Interface_P.Manager_Access := null; end record; procedure Adjust (Object : in out Manager); procedure Finalize (Object : in out Manager); end Util.Properties;
Update the Manager_Access to be class-wide access type
Update the Manager_Access to be class-wide access type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
eab8677850148f73159595c2801b12b5eec50f34
demo/texture.adb
demo/texture.adb
-- Simple Lumen demo/test program, using earliest incomplete library. with Ada.Command_Line; with System.Address_To_Access_Conversions; with Lumen.Events.Animate; with Lumen.Image; with Lumen.Window; with GL; with GLU; procedure Texture is --------------------------------------------------------------------------- -- Rotation wraps around at this point, in degrees Max_Rotation : constant := 359; -- Traditional cinema framrate, in frames per second Framerate : constant := 24; --------------------------------------------------------------------------- Win : Lumen.Window.Handle; Direct : Boolean := True; -- want direct rendering by default Event : Lumen.Events.Event_Data; Wide : Natural; -- no longer have default values since they're now set by the image size High : Natural; Rotation : Natural := 0; Image : Lumen.Image.Descriptor; Img_Wide : GL.glFloat; Img_High : GL.glFloat; Tx_Name : aliased GL.GLuint; Attrs : Lumen.Window.Context_Attributes := ( (Lumen.Window.Attr_Red_Size, 8), (Lumen.Window.Attr_Green_Size, 8), (Lumen.Window.Attr_Blue_Size, 8), (Lumen.Window.Attr_Alpha_Size, 8), (Lumen.Window.Attr_Depth_Size, 24), (Lumen.Window.Attr_Stencil_Size, 8) ); --------------------------------------------------------------------------- Program_Error : exception; Program_Exit : exception; --------------------------------------------------------------------------- -- Create a texture and bind a 2D image to it procedure Create_Texture is use GL; use GLU; package GLB is new System.Address_To_Access_Conversions (GLubyte); IP : GLpointer; begin -- Create_Texture -- Allocate a texture name glGenTextures (1, Tx_Name'Unchecked_Access); -- Bind texture operations to the newly-created texture name glBindTexture (GL_TEXTURE_2D, Tx_Name); -- Select modulate to mix texture with color for shading glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); -- Wrap textures at both edges glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); -- How the texture behaves when minified and magnified glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); -- Create a pointer to the image. This sort of horror show is going to -- be disappearing once Lumen includes its own OpenGL bindings. IP := GLB.To_Pointer (Image.Values.all'Address).all'Unchecked_Access; -- Build our texture from the image we loaded earlier glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0, GL_RGBA, GL_UNSIGNED_BYTE, IP); end Create_Texture; --------------------------------------------------------------------------- -- Set or reset the window view parameters procedure Set_View (W, H : in Natural) is use GL; use GLU; Aspect : GLdouble; begin -- Set_View -- Viewport dimensions glViewport (0, 0, GLsizei (W), GLsizei (H)); -- Size of rectangle upon which image is mapped if Wide > High then Img_Wide := glFloat (1.5); Img_High := glFloat (1.5) * glFloat (Float (High) / Float (Wide)); else Img_Wide := glFloat (1.5) * glFloat (Float (Wide) / Float (High)); Img_High := glFloat (1.5); end if; -- Set up the projection matrix based on the window's shape--wider than -- high, or higher than wide glMatrixMode (GL_PROJECTION); glLoadIdentity; -- Set up a 3D viewing frustum, which is basically a truncated pyramid -- in which the scene takes place. Roughly, the narrow end is your -- screen, and the wide end is 10 units away from the camera. if W <= H then Aspect := GLdouble (H) / GLdouble (W); glFrustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0); else Aspect := GLdouble (W) / GLdouble (H); glFrustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0); end if; end Set_View; --------------------------------------------------------------------------- -- Draw our scene procedure Draw is use GL; begin -- Draw -- Set a light grey background glClearColor (0.8, 0.8, 0.8, 1.0); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); -- Draw a texture-mapped rectangle with the same aspect ratio as the -- original image glBegin (GL_POLYGON); begin glTexCoord3f (0.0, 1.0, 0.0); glVertex3f (-Img_Wide, -Img_High, 0.0); glTexCoord3f (0.0, 0.0, 0.0); glVertex3f (-Img_Wide, Img_High, 0.0); glTexCoord3f (1.0, 0.0, 0.0); glVertex3f ( Img_Wide, Img_High, 0.0); glTexCoord3f (1.0, 1.0, 0.0); glVertex3f ( Img_Wide, -Img_High, 0.0); end; glEnd; -- Rotate the object around the Y and Z axes by the current amount, to -- give a "tumbling" effect. glMatrixMode (GL_MODELVIEW); glLoadIdentity; glTranslated (0.0, 0.0, -4.0); glRotated (GLdouble (Rotation), 0.0, 1.0, 0.0); glRotated (GLdouble (Rotation), 0.0, 0.0, 1.0); glFlush; -- Now show it Lumen.Window.Swap (Win); end Draw; --------------------------------------------------------------------------- -- Simple event handler routine for keypresses and close-window events procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin -- Quit_Handler raise Program_Exit; end Quit_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Exposed events procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is begin -- Expose_Handler Draw; end Expose_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Resized events procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is begin -- Resize_Handler Wide := Event.Resize_Data.Width; High := Event.Resize_Data.Height; Set_View (Wide, High); Draw; end Resize_Handler; --------------------------------------------------------------------------- -- Our draw-a-frame routine, should get called FPS times a second procedure New_Frame (Frame_Delta : in Duration) is begin -- New_Frame if Rotation >= Max_Rotation then Rotation := 0; else Rotation := Rotation + 1; end if; Draw; end New_Frame; --------------------------------------------------------------------------- begin -- Texture -- If we haven't been given an image to work with, just do nothing if Ada.Command_Line.Argument_Count < 1 then raise Program_Error with "You did not supply an image file pathname on the command line"; end if; -- If other command-line arguments were given then process them for Index in 2 .. Ada.Command_Line.Argument_Count loop declare use Lumen.Window; Arg : String := Ada.Command_Line.Argument (Index); begin case Arg (Arg'First) is when 'a' => Attrs (4) := (Attr_Alpha_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); when 'c' => Attrs (1) := (Attr_Red_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); Attrs (2) := (Attr_Blue_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); Attrs (3) := (Attr_Green_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); when 'd' => Attrs (5) := (Attr_Depth_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); when 'n' => Direct := False; when others => null; end case; end; end loop; -- Read image and use it to size the window. This will suck if your image -- is very large. Image := Lumen.Image.From_File (Ada.Command_Line.Argument (1)); Wide := Image.Width; High := Image.Height; -- Create Lumen window, accepting most defaults; turn double buffering off -- for simplicity Lumen.Window.Create (Win, Name => "Spinning Picture Demo", Width => Wide, Height => High, Direct => Direct, Attributes => Attrs, Events => (Lumen.Window.Want_Key_Press => True, Lumen.Window.Want_Exposure => True, others => False)); -- Set up the viewport and scene parameters Set_View (Wide, High); -- Now create the texture and set up to use it Create_Texture; GL.glEnable (GL.GL_TEXTURE_2D); GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name); -- Enter the event loop declare use Lumen.Events; begin Animate.Select_Events (Win => Win, Calls => (Key_Press => Quit_Handler'Unrestricted_Access, Exposed => Expose_Handler'Unrestricted_Access, Resized => Resize_Handler'Unrestricted_Access, Close_Window => Quit_Handler'Unrestricted_Access, others => No_Callback), FPS => Framerate, Frame => New_Frame'Unrestricted_Access); end; exception when Program_Exit => null; -- just exit this block, which terminates the app end Texture;
-- Simple Lumen demo/test program, using earliest incomplete library. with Ada.Command_Line; with System.Address_To_Access_Conversions; with Lumen.Events.Animate; with Lumen.Image; with Lumen.Window; with GL; with GLU; procedure Texture is --------------------------------------------------------------------------- -- Rotation wraps around at this point, in degrees Max_Rotation : constant := 359; -- Traditional cinema framrate, in frames per second Framerate : constant := 24; --------------------------------------------------------------------------- Win : Lumen.Window.Handle; Direct : Boolean := True; -- want direct rendering by default Event : Lumen.Events.Event_Data; Wide : Natural; -- no longer have default values since they're now set by the image size High : Natural; Rotation : Natural := 0; Image : Lumen.Image.Descriptor; Img_Wide : GL.glFloat; Img_High : GL.glFloat; Tx_Name : aliased GL.GLuint; Attrs : Lumen.Window.Context_Attributes := ( (Lumen.Window.Attr_Red_Size, 8), (Lumen.Window.Attr_Green_Size, 8), (Lumen.Window.Attr_Blue_Size, 8), (Lumen.Window.Attr_Alpha_Size, 8), (Lumen.Window.Attr_Depth_Size, 24), (Lumen.Window.Attr_Stencil_Size, 8) ); --------------------------------------------------------------------------- Program_Error : exception; --------------------------------------------------------------------------- -- Create a texture and bind a 2D image to it procedure Create_Texture is use GL; use GLU; package GLB is new System.Address_To_Access_Conversions (GLubyte); IP : GLpointer; begin -- Create_Texture -- Allocate a texture name glGenTextures (1, Tx_Name'Unchecked_Access); -- Bind texture operations to the newly-created texture name glBindTexture (GL_TEXTURE_2D, Tx_Name); -- Select modulate to mix texture with color for shading glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); -- Wrap textures at both edges glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); -- How the texture behaves when minified and magnified glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); -- Create a pointer to the image. This sort of horror show is going to -- be disappearing once Lumen includes its own OpenGL bindings. IP := GLB.To_Pointer (Image.Values.all'Address).all'Unchecked_Access; -- Build our texture from the image we loaded earlier glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0, GL_RGBA, GL_UNSIGNED_BYTE, IP); end Create_Texture; --------------------------------------------------------------------------- -- Set or reset the window view parameters procedure Set_View (W, H : in Natural) is use GL; use GLU; Aspect : GLdouble; begin -- Set_View -- Viewport dimensions glViewport (0, 0, GLsizei (W), GLsizei (H)); -- Size of rectangle upon which image is mapped if Wide > High then Img_Wide := glFloat (1.5); Img_High := glFloat (1.5) * glFloat (Float (High) / Float (Wide)); else Img_Wide := glFloat (1.5) * glFloat (Float (Wide) / Float (High)); Img_High := glFloat (1.5); end if; -- Set up the projection matrix based on the window's shape--wider than -- high, or higher than wide glMatrixMode (GL_PROJECTION); glLoadIdentity; -- Set up a 3D viewing frustum, which is basically a truncated pyramid -- in which the scene takes place. Roughly, the narrow end is your -- screen, and the wide end is 10 units away from the camera. if W <= H then Aspect := GLdouble (H) / GLdouble (W); glFrustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0); else Aspect := GLdouble (W) / GLdouble (H); glFrustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0); end if; end Set_View; --------------------------------------------------------------------------- -- Draw our scene procedure Draw is use GL; begin -- Draw -- Set a light grey background glClearColor (0.8, 0.8, 0.8, 1.0); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); -- Draw a texture-mapped rectangle with the same aspect ratio as the -- original image glBegin (GL_POLYGON); begin glTexCoord3f (0.0, 1.0, 0.0); glVertex3f (-Img_Wide, -Img_High, 0.0); glTexCoord3f (0.0, 0.0, 0.0); glVertex3f (-Img_Wide, Img_High, 0.0); glTexCoord3f (1.0, 0.0, 0.0); glVertex3f ( Img_Wide, Img_High, 0.0); glTexCoord3f (1.0, 1.0, 0.0); glVertex3f ( Img_Wide, -Img_High, 0.0); end; glEnd; -- Rotate the object around the Y and Z axes by the current amount, to -- give a "tumbling" effect. glMatrixMode (GL_MODELVIEW); glLoadIdentity; glTranslated (0.0, 0.0, -4.0); glRotated (GLdouble (Rotation), 0.0, 1.0, 0.0); glRotated (GLdouble (Rotation), 0.0, 0.0, 1.0); glFlush; -- Now show it Lumen.Window.Swap (Win); end Draw; --------------------------------------------------------------------------- -- Simple event handler routine for keypresses and close-window events procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin -- Quit_Handler Lumen.Events.End_Events (Win); end Quit_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Exposed events procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is begin -- Expose_Handler Draw; end Expose_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Resized events procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is begin -- Resize_Handler Wide := Event.Resize_Data.Width; High := Event.Resize_Data.Height; Set_View (Wide, High); Draw; end Resize_Handler; --------------------------------------------------------------------------- -- Our draw-a-frame routine, should get called FPS times a second procedure New_Frame (Frame_Delta : in Duration) is begin -- New_Frame if Rotation >= Max_Rotation then Rotation := 0; else Rotation := Rotation + 1; end if; Draw; end New_Frame; --------------------------------------------------------------------------- begin -- Texture -- If we haven't been given an image to work with, just do nothing if Ada.Command_Line.Argument_Count < 1 then raise Program_Error with "You did not supply an image file pathname on the command line"; end if; -- If other command-line arguments were given then process them for Index in 2 .. Ada.Command_Line.Argument_Count loop declare use Lumen.Window; Arg : String := Ada.Command_Line.Argument (Index); begin case Arg (Arg'First) is when 'a' => Attrs (4) := (Attr_Alpha_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); when 'c' => Attrs (1) := (Attr_Red_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); Attrs (2) := (Attr_Blue_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); Attrs (3) := (Attr_Green_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); when 'd' => Attrs (5) := (Attr_Depth_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last))); when 'n' => Direct := False; when others => null; end case; end; end loop; -- Read image and use it to size the window. This will suck if your image -- is very large. Image := Lumen.Image.From_File (Ada.Command_Line.Argument (1)); Wide := Image.Width; High := Image.Height; -- Create Lumen window, accepting most defaults; turn double buffering off -- for simplicity Lumen.Window.Create (Win, Name => "Spinning Picture Demo", Width => Wide, Height => High, Direct => Direct, Attributes => Attrs, Events => (Lumen.Window.Want_Key_Press => True, Lumen.Window.Want_Exposure => True, others => False)); -- Set up the viewport and scene parameters Set_View (Wide, High); -- Now create the texture and set up to use it Create_Texture; GL.glEnable (GL.GL_TEXTURE_2D); GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name); -- Enter the event loop, which will terminate when the Quit_Handler calls End_Events declare use Lumen.Events; begin Animate.Select_Events (Win => Win, Calls => (Key_Press => Quit_Handler'Unrestricted_Access, Exposed => Expose_Handler'Unrestricted_Access, Resized => Resize_Handler'Unrestricted_Access, Close_Window => Quit_Handler'Unrestricted_Access, others => No_Callback), FPS => Framerate, Frame => New_Frame'Unrestricted_Access); end; -- Try these just to make sure they work Lumen.Window.Destroy_Context (Win); Lumen.Window.Destroy (Win); end Texture;
Adjust this demo to use alternate method of ending an app, by calling End_Events
Adjust this demo to use alternate method of ending an app, by calling End_Events
Ada
isc
darkestkhan/lumen2,darkestkhan/lumen
ce1c357f623b86ca57486ff927ec346b63f3ad66
matp/src/mat-targets.adb
matp/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- 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.Text_IO; with Ada.Command_Line; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- 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.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- 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 is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- 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)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- 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 is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [-s path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-s path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b: s:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 's' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- 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) is begin loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- 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.Text_IO; with Ada.Command_Line; with Ada.Unchecked_Deallocation; with GNAT.Command_Line; with Readline; with Util.Strings; with Util.Log.Loggers; with MAT.Commands; with MAT.Targets.Probes; package body MAT.Targets is procedure Free is new Ada.Unchecked_Deallocation (MAT.Events.Targets.Target_Events'Class, MAT.Events.Targets.Target_Events_Access); procedure Free is new Ada.Unchecked_Deallocation (Target_Process_Type'Class, Target_Process_Type_Access); -- ------------------------------ -- Release the target process instance. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Process_Type) is begin Free (Target.Events); end Finalize; -- ------------------------------ -- Find the region that matches the given name. -- ------------------------------ overriding function Find_Region (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is begin return Resolver.Memory.Find_Region (Name); end Find_Region; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ overriding function Find_Symbol (Resolver : in Target_Process_Type; Name : in String) return MAT.Memory.Region_Info is Region : MAT.Memory.Region_Info; begin if Resolver.Symbols.Is_Null then raise MAT.Memory.Targets.Not_Found; end if; Resolver.Symbols.Value.Find_Symbol_Range (Name, Region.Start_Addr, Region.End_Addr); return Region; end Find_Symbol; -- ------------------------------ -- Get the start time for the tick reference. -- ------------------------------ overriding function Get_Start_Time (Resolver : in Target_Process_Type) return MAT.Types.Target_Tick_Ref is Start : MAT.Types.Target_Tick_Ref; Finish : MAT.Types.Target_Tick_Ref; begin Resolver.Events.Get_Time_Range (Start, Finish); return Start; end Get_Start_Time; -- ------------------------------ -- Get the console instance. -- ------------------------------ function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is begin return Target.Console; end Console; -- ------------------------------ -- Set the console instance. -- ------------------------------ procedure Console (Target : in out Target_Type; Console : in MAT.Consoles.Console_Access) is begin Target.Console := Console; end Console; -- ------------------------------ -- Get the current process instance. -- ------------------------------ function Process (Target : in Target_Type) return Target_Process_Type_Access is begin return Target.Current; end Process; -- ------------------------------ -- 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.Events.Probes.Probe_Manager_Type'Class) is begin MAT.Targets.Probes.Initialize (Target => Target, Manager => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String; Process : out Target_Process_Type_Access) is Path_String : constant String := Ada.Strings.Unbounded.To_String (Path); begin Process := Target.Find_Process (Pid); if Process = null then Process := new Target_Process_Type; Process.Pid := Pid; Process.Path := Path; Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create; Process.Symbols.Value.Console := Target.Console; Process.Symbols.Value.Search_Path := Target.Options.Search_Path; Target.Processes.Insert (Pid, Process); Target.Console.Notice (MAT.Consoles.N_PID_INFO, "Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created"); Target.Console.Notice (MAT.Consoles.N_PATH_INFO, "Path " & Path_String); end if; if Target.Current = null then Target.Current := Process; end if; end Create_Process; -- ------------------------------ -- 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 is Pos : constant Process_Cursor := Target.Processes.Find (Pid); begin if Process_Maps.Has_Element (Pos) then return Process_Maps.Element (Pos); else return null; end if; end Find_Process; -- ------------------------------ -- 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)) is Iter : Process_Cursor := Target.Processes.First; begin while Process_Maps.Has_Element (Iter) loop Process (Process_Maps.Element (Iter).all); Process_Maps.Next (Iter); end loop; end Iterator; -- ------------------------------ -- 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 is Pos : constant Natural := Util.Strings.Index (Param, ':'); Result : GNAT.Sockets.Sock_Addr_Type; begin if Pos > 0 then Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last)); Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1)); else Result.Port := GNAT.Sockets.Port_Type'Value (Param); Result.Addr := GNAT.Sockets.Any_Inet_Addr; end if; return Result; end To_Sock_Addr_Type; -- ------------------------------ -- Print the application usage. -- ------------------------------ procedure Usage is use Ada.Text_IO; begin Put_Line ("Usage: mat [-i] [-e] [-nw] [-ns] [-b [ip:]port] [-s path] [file.mat]"); Put_Line ("-i Enable the interactive mode"); Put_Line ("-e Print the probe events as they are received"); Put_Line ("-nw Disable the graphical mode"); Put_Line ("-b [ip:]port Define the port and local address to bind"); Put_Line ("-ns Disable the automatic symbols loading"); Put_Line ("-s path Search path to find shared libraries and load their symbols"); Ada.Command_Line.Set_Exit_Status (2); raise Usage_Error; end Usage; -- ------------------------------ -- Add a search path for the library and symbol loader. -- ------------------------------ procedure Add_Search_Path (Target : in out MAT.Targets.Target_Type; Path : in String) is begin if Ada.Strings.Unbounded.Length (Target.Options.Search_Path) > 0 then Ada.Strings.Unbounded.Append (Target.Options.Search_Path, ";"); Ada.Strings.Unbounded.Append (Target.Options.Search_Path, Path); else Target.Options.Search_Path := Ada.Strings.Unbounded.To_Unbounded_String (Path); end if; end Add_Search_Path; -- ------------------------------ -- Parse the command line arguments and configure the target instance. -- ------------------------------ procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is begin Util.Log.Loggers.Initialize ("matp.properties"); GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); loop case GNAT.Command_Line.Getopt ("i e nw ns b: s:") is when ASCII.NUL => exit; when 'i' => Target.Options.Interactive := True; when 'e' => Target.Options.Print_Events := True; when 'b' => Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter); when 'n' => if GNAT.Command_Line.Full_Switch = "nw" then Target.Options.Graphical := False; else Target.Options.Load_Symbols := False; end if; when 's' => Add_Search_Path (Target, GNAT.Command_Line.Parameter); when '*' => exit; when others => Usage; end case; end loop; exception when Usage_Error => raise; when others => Usage; end Initialize_Options; -- ------------------------------ -- 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) is begin loop declare Line : constant String := Readline.Get_Line ("matp>"); begin MAT.Commands.Execute (Target, Line); exception when MAT.Commands.Stop_Interp => exit; end; end loop; end Interactive; -- ------------------------------ -- Start the server to listen to MAT event socket streams. -- ------------------------------ procedure Start (Target : in out Target_Type) is begin Target.Server.Start (Target'Unchecked_Access, Target.Options.Address); end Start; -- ------------------------------ -- Stop the server thread. -- ------------------------------ procedure Stop (Target : in out Target_Type) is begin Target.Server.Stop; end Stop; -- ------------------------------ -- Release the storage used by the target object. -- ------------------------------ overriding procedure Finalize (Target : in out Target_Type) is begin while not Target.Processes.Is_Empty loop declare Process : Target_Process_Type_Access := Target.Processes.First_Element; begin Free (Process); Target.Processes.Delete_First; end; end loop; end Finalize; end MAT.Targets;
Implement the Get_Start_Time function
Implement the Get_Start_Time function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0ee3f9a26d0e16fe06076e2bda7bdcfef4716bdc
src/ado-databases.adb
src/ado-databases.adb
----------------------------------------------------------------------- -- ADO Databases -- Database Connections -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Statements.Create; package body ADO.Databases is use Util.Log; use ADO.Drivers; use type ADO.Drivers.Connections.Database_Connection_Access; Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases"); -- ------------------------------ -- Get the database connection status. -- ------------------------------ function Get_Status (Database : in Connection) return Connection_Status is begin if Database.Impl = null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; declare Query : constant Query_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Connection; Query : in String) return Query_Statement is begin if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; declare Stmt : constant Query_Statement_Access := Database.Impl.all.Create_Statement (null); begin Append (Query => Stmt.all, SQL => Query); return ADO.Statements.Create.Create_Statement (Stmt); end; end Create_Statement; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Connection) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; return Database.Impl.Get_Driver; end Get_Driver; -- ------------------------------ -- Get the database driver index. -- ------------------------------ function Get_Driver_Index (Database : in Connection) return ADO.Drivers.Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database.Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; -- ------------------------------ -- Get a database connection identifier. -- ------------------------------ function Get_Ident (Database : in Connection) return String is begin if Database.Impl = null then return "null"; else return Database.Impl.Ident; end if; end Get_Ident; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Connection; Schema : out ADO.Schemas.Schema_Definition) is begin if Database.Impl = null then Log.Error ("Database connection is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Load_Schema (Schema); end Load_Schema; -- ------------------------------ -- Close the database connection -- ------------------------------ procedure Close (Database : in out Connection) is begin Log.Info ("Closing database connection {0}", Database.Get_Ident); if Database.Impl /= null then Database.Impl.Close; end if; end Close; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Connection) is begin Log.Info ("Begin transaction {0}", Database.Get_Ident); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Connection) is begin Log.Info ("Commit transaction {0}", Database.Get_Ident); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Connection) is begin Log.Info ("Rollback transaction {0}", Database.Get_Ident); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "Database implementation is not initialized"; end if; Database.Impl.Rollback; end Rollback; -- ------------------------------ -- Create a delete statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Log.Debug ("Create delete statement {0}", Database.Get_Ident); declare Stmt : constant Delete_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt); end; end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Log.Debug ("Create insert statement {0}", Database.Get_Ident); declare Stmt : constant Insert_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Log.Debug ("Create update statement {0}", Database.Get_Ident); return ADO.Statements.Create.Create_Statement (Database.Impl.all.Create_Statement (Table)); end Create_Statement; -- ------------------------------ -- Adjust the connection reference counter -- ------------------------------ overriding procedure Adjust (Object : in out Connection) is begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count + 1; end if; end Adjust; -- ------------------------------ -- Releases the connection reference counter -- ------------------------------ overriding procedure Finalize (Object : in out Connection) is procedure Free is new Ada.Unchecked_Deallocation (Object => ADO.Drivers.Connections.Database_Connection'Class, Name => ADO.Drivers.Connections.Database_Connection_Access); begin if Object.Impl /= null then Object.Impl.Count := Object.Impl.Count - 1; if Object.Impl.Count = 0 then Free (Object.Impl); end if; end if; end Finalize; -- ------------------------------ -- Attempts to establish a connection with the data source -- that this DataSource object represents. -- ------------------------------ function Get_Connection (Controller : in DataSource) return Master_Connection'Class is Connection : ADO.Drivers.Connections.Database_Connection_Access; begin Log.Info ("Get master connection from data-source"); Controller.Create_Connection (Connection); return Master_Connection '(Ada.Finalization.Controlled with Impl => Connection); end Get_Connection; -- ------------------------------ -- Set the master data source -- ------------------------------ procedure Set_Master (Controller : in out Replicated_DataSource; Master : in DataSource_Access) is begin Controller.Master := Master; end Set_Master; -- ------------------------------ -- Get the master data source -- ------------------------------ function Get_Master (Controller : in Replicated_DataSource) return DataSource_Access is begin return Controller.Master; end Get_Master; -- ------------------------------ -- Set the slave data source -- ------------------------------ procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in DataSource_Access) is begin Controller.Slave := Slave; end Set_Slave; -- ------------------------------ -- Get the slave data source -- ------------------------------ function Get_Slave (Controller : in Replicated_DataSource) return DataSource_Access is begin return Controller.Slave; end Get_Slave; -- ------------------------------ -- Get a slave database connection -- ------------------------------ function Get_Slave_Connection (Controller : in Replicated_DataSource) return Connection'Class is begin return Controller.Slave.Get_Connection; end Get_Slave_Connection; end ADO.Databases;
----------------------------------------------------------------------- -- ADO Databases -- Database Connections -- Copyright (C) 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Statements.Create; package body ADO.Databases is use ADO.Drivers; use type ADO.Drivers.Connections.Database_Connection_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases"); -- ------------------------------ -- Get the database connection status. -- ------------------------------ function Get_Status (Database : in Connection) return Connection_Status is begin if Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin if Database.Is_Null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; declare Query : constant Query_Statement_Access := Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Connection; Query : in String) return Query_Statement is begin if Database.Is_Null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; declare Stmt : constant Query_Statement_Access := Database.Value.all.Create_Statement (null); begin Append (Query => Stmt.all, SQL => Query); return ADO.Statements.Create.Create_Statement (Stmt); end; end Create_Statement; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Connection) return ADO.Drivers.Connections.Driver_Access is begin if Database.Is_Null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; return Database.Value.Get_Driver; end Get_Driver; -- ------------------------------ -- Get the database driver index. -- ------------------------------ function Get_Driver_Index (Database : in Connection) return ADO.Drivers.Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database.Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; -- ------------------------------ -- Get a database connection identifier. -- ------------------------------ function Get_Ident (Database : in Connection) return String is begin if Database.Is_Null then return "null"; else return Database.Value.Ident; end if; end Get_Ident; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Connection; Schema : out ADO.Schemas.Schema_Definition) is begin if Database.Is_Null then Log.Error ("Database connection is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Value.Load_Schema (Schema); end Load_Schema; -- ------------------------------ -- Close the database connection -- ------------------------------ procedure Close (Database : in out Connection) is begin Log.Info ("Closing database connection {0}", Database.Get_Ident); if not Database.Is_Null then Database.Value.Close; end if; end Close; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Connection) is begin Log.Info ("Begin transaction {0}", Database.Get_Ident); if Database.Is_Null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Connection) is begin Log.Info ("Commit transaction {0}", Database.Get_Ident); if Database.Is_Null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Connection) is begin Log.Info ("Rollback transaction {0}", Database.Get_Ident); if Database.Is_Null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "Database implementation is not initialized"; end if; Database.Value.Rollback; end Rollback; -- ------------------------------ -- Create a delete statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Log.Debug ("Create delete statement {0}", Database.Get_Ident); declare Stmt : constant Delete_Statement_Access := Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt); end; end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Log.Debug ("Create insert statement {0}", Database.Get_Ident); declare Stmt : constant Insert_Statement_Access := Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Log.Debug ("Create update statement {0}", Database.Get_Ident); return ADO.Statements.Create.Create_Statement (Database.Value.all.Create_Statement (Table)); end Create_Statement; -- ------------------------------ -- Attempts to establish a connection with the data source -- that this DataSource object represents. -- ------------------------------ function Get_Connection (Controller : in DataSource) return Master_Connection'Class is Connection : Master_Connection; -- ADO.Drivers.Connections.Database_Connection_Access; begin Log.Info ("Get master connection from data-source"); Controller.Create_Connection (Connection); return Connection; end Get_Connection; -- ------------------------------ -- Set the master data source -- ------------------------------ procedure Set_Master (Controller : in out Replicated_DataSource; Master : in DataSource_Access) is begin Controller.Master := Master; end Set_Master; -- ------------------------------ -- Get the master data source -- ------------------------------ function Get_Master (Controller : in Replicated_DataSource) return DataSource_Access is begin return Controller.Master; end Get_Master; -- ------------------------------ -- Set the slave data source -- ------------------------------ procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in DataSource_Access) is begin Controller.Slave := Slave; end Set_Slave; -- ------------------------------ -- Get the slave data source -- ------------------------------ function Get_Slave (Controller : in Replicated_DataSource) return DataSource_Access is begin return Controller.Slave; end Get_Slave; -- ------------------------------ -- Get a slave database connection -- ------------------------------ function Get_Slave_Connection (Controller : in Replicated_DataSource) return Connection'Class is begin return Controller.Slave.Get_Connection; end Get_Slave_Connection; end ADO.Databases;
Update the implementation to use the reference counted connection
Update the implementation to use the reference counted connection
Ada
apache-2.0
stcarrez/ada-ado
8eb99fd098d0f3f56cdc28fef247c707bd12758a
awa/plugins/awa-blogs/src/awa-blogs-services.adb
awa/plugins/awa-blogs/src/awa-blogs-services.adb
----------------------------------------------------------------------- -- awa-blogs-services -- Blogs and post management -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Blogs.Models; 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; with Util.Log.Loggers; -- The <b>Blogs.Services</b> package defines the service and operations to -- create, update and delete a post. package body AWA.Blogs.Services is use AWA.Services; use ADO.Sessions; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Blogs.Services"); -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Service; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : 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.Get_Id); 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_Service; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : 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_Blog.Permission, Entity => Blog_Id); -- 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.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_Service; Post_Id : in ADO.Identifier; Title : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : 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_Id); Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Status (Status); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : 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_Id); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Services;
----------------------------------------------------------------------- -- awa-blogs-services -- Blogs and post management -- 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 AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with ADO.Sessions; with Ada.Calendar; with Util.Log.Loggers; -- The <b>Blogs.Services</b> package defines the service and operations to -- create, update and delete a post. package body AWA.Blogs.Services is use AWA.Services; use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Services"); -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Service; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : 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_Service; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : 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_Blog.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.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_Service; Post_Id : in ADO.Identifier; Title : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : 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_Status (Status); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : 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.Services;
Change checking the permission to use the database Object_Ref
Change checking the permission to use the database Object_Ref
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4816082a35a1c5ae1ab437cc099b60c0367699f5
src/asf-rest.adb
src/asf-rest.adb
----------------------------------------------------------------------- -- asf-rest -- REST Support -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Routes; with ASF.Routes.Servlets.Rest; with ASF.Servlets.Rest; with Util.Log.Loggers; package body ASF.Rest is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Rest"); -- ------------------------------ -- Get the permission index associated with the REST operation. -- ------------------------------ function Get_Permission (Handler : in Descriptor) return Security.Permissions.Permission_Index is begin return Handler.Permission; end Get_Permission; -- ------------------------------ -- Register the API descriptor in a list. -- ------------------------------ procedure Register (List : in out Descriptor_Access; Item : in Descriptor_Access) is begin Item.Next := List; List := Item; end Register; -- ------------------------------ -- Register the list of API descriptors for a given servlet and a root path. -- ------------------------------ procedure Register (Registry : in out ASF.Servlets.Servlet_Registry; Name : in String; URI : in String; ELContext : in EL.Contexts.ELContext'Class; List : in Descriptor_Access) is use type ASF.Routes.Route_Type_Access; Item : Descriptor_Access := List; procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is R : ASF.Routes.Route_Type_Access := Route.Value; D : ASF.Routes.Servlets.Rest.API_Route_Type_Access; begin if R /= null then if not (R.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then Log.Error ("Route API for {0}/{1} already used by another page", URI, Item.Pattern.all); return; end if; D := ASF.Routes.Servlets.Rest.API_Route_Type (R.all)'Access; else D := ASF.Servlets.Rest.Create_Route (Registry, Name); Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access); end if; if D.Descriptors (Item.Method) /= null then Log.Error ("Route API for {0}/{1} is already used", URI, Item.Pattern.all); end if; D.Descriptors (Item.Method) := Item; end Insert; begin Log.Info ("Adding API route {0}", URI); while Item /= null loop Log.Debug ("Adding API route {0}/{1}", URI, Item.Pattern.all); Registry.Add_Route (URI & "/" & Item.Pattern.all, ELContext, Insert'Access); Item := Item.Next; end loop; end Register; end ASF.Rest;
----------------------------------------------------------------------- -- asf-rest -- REST Support -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Routes; with ASF.Routes.Servlets.Rest; with ASF.Servlets.Rest; with Util.Log.Loggers; package body ASF.Rest is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Rest"); -- ------------------------------ -- Get the permission index associated with the REST operation. -- ------------------------------ function Get_Permission (Handler : in Descriptor) return Security.Permissions.Permission_Index is begin return Handler.Permission; end Get_Permission; -- ------------------------------ -- Register the API descriptor in a list. -- ------------------------------ procedure Register (List : in out Descriptor_Access; Item : in Descriptor_Access) is begin Item.Next := List; List := Item; end Register; -- ------------------------------ -- Register the list of API descriptors for a given servlet and a root path. -- ------------------------------ procedure Register (Registry : in out ASF.Servlets.Servlet_Registry; Name : in String; URI : in String; ELContext : in EL.Contexts.ELContext'Class; List : in Descriptor_Access) is procedure Insert (Route : in out ASF.Routes.Route_Type_Ref); use type ASF.Routes.Route_Type_Access; Item : Descriptor_Access := List; procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is R : constant ASF.Routes.Route_Type_Access := Route.Value; D : ASF.Routes.Servlets.Rest.API_Route_Type_Access; begin if R /= null then if not (R.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then Log.Error ("Route API for {0}/{1} already used by another page", URI, Item.Pattern.all); return; end if; D := ASF.Routes.Servlets.Rest.API_Route_Type (R.all)'Access; else D := ASF.Servlets.Rest.Create_Route (Registry, Name); Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access); end if; if D.Descriptors (Item.Method) /= null then Log.Error ("Route API for {0}/{1} is already used", URI, Item.Pattern.all); end if; D.Descriptors (Item.Method) := Item; end Insert; begin Log.Info ("Adding API route {0}", URI); while Item /= null loop Log.Debug ("Adding API route {0}/{1}", URI, Item.Pattern.all); Registry.Add_Route (URI & "/" & Item.Pattern.all, ELContext, Insert'Access); Item := Item.Next; end loop; end Register; end ASF.Rest;
Declare the Insert procedure and make the R local variable constant
Declare the Insert procedure and make the R local variable constant
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
271b0feccd10febcb967af7703546c824eaa71af
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions"); -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Permissions.Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- ------------------------------ procedure Set_Reader_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Set_Reader_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is use Util.Log; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions"); -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- ------------------------------ procedure Set_Reader_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : Controller_Config_Access := new Controller_Config; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config_Mapper.Set_Context (Reader, Config); end Set_Reader_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Fix compilation
Fix compilation
Ada
apache-2.0
Letractively/ada-security
a44e611b1e8660653e3b11052e4e2ccb011e25f9
awa/src/awa-applications.adb
awa/src/awa-applications.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ADO.Drivers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with ASF.Server; with ASF.Servlets; with AWA.Services.Contexts; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; with AWA.Helpers.Selectors; with AWA.Permissions.Services; with AWA.Permissions.Beans; package body AWA.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Initializing application"); Ctx.Set_Context (App'Unchecked_Access, null); AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); -- Load the application configuration before any module. Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P)); -- Register the application modules and load their configuration. Application'Class (App).Initialize_Modules; -- Load the plugin application configuration after the module are configured. Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P)); end Initialize; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is begin Log.Info ("Initializing configuration"); if Conf.Get ("app.modules.dir", "") = "" then Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}"); end if; if Conf.Get ("bundle.dir", "") = "" then Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}"); end if; if Conf.Get ("ado.queries.paths", "") = "" then Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}"); end if; ASF.Applications.Main.Application (App).Initialize_Config (Conf); ADO.Drivers.Initialize (Conf); App.DB_Factory.Create (Conf.Get ("database")); App.Events.Initialize (App'Unchecked_Access); AWA.Modules.Initialize (App.Modules, Conf); App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean", AWA.Helpers.Selectors.Create_Select_List_Bean'Access); App.Register_Class ("AWA.Permissions.Beans.Permission_Bean", AWA.Permissions.Beans.Create_Permission_Bean'Access); end Initialize_Config; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin Log.Info ("Initializing application servlets"); ASF.Applications.Main.Application (App).Initialize_Servlets; end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters"); ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is procedure Register_Functions is new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions); begin Log.Info ("Initializing application components"); ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); Register_Functions (App); end Initialize_Components; -- ------------------------------ -- Read the application configuration file <b>awa.xml</b>. This is called after the servlets -- and filters have been registered in the application but before the module registration. -- ------------------------------ procedure Load_Configuration (App : in out Application; Files : in String) is procedure Load_Config (File : in String; Done : out Boolean); Paths : constant String := App.Get_Config (P_Module_Dir.P); Ctx : aliased EL.Contexts.Default.Default_Context; procedure Load_Config (File : in String; Done : out Boolean) is Path : constant String := Util.Files.Find_File_Path (File, Paths); begin Done := False; AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access, True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Config; begin Util.Files.Iterate_Path (Files, Load_Config'Access); end Load_Configuration; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Start the application. This is called by the server container when the server is started. -- ------------------------------ overriding procedure Start (App : in out Application) is begin -- Start the event service. App.Events.Start; -- Start the application. ASF.Applications.Main.Application (App).Start; -- Dump the route and filters to help in configuration issues. App.Dump_Routes (Util.Log.INFO_LEVEL); end Start; -- ------------------------------ -- Close the application. -- ------------------------------ overriding procedure Close (App : in out Application) is begin App.Events.Stop; ASF.Applications.Main.Application (App).Close; end Close; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is begin AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); end Register; -- ------------------------------ -- Send the event in the application event queues. -- ------------------------------ procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class) is begin App.Events.Send (Event); end Send_Event; -- ------------------------------ -- Execute the <tt>Process</tt> procedure with the event manager used by the application. -- ------------------------------ procedure Do_Event_Manager (App : in out Application; Process : access procedure (Events : in out AWA.Events.Services.Event_Manager)) is begin Process (App.Events); end Do_Event_Manager; -- ------------------------------ -- Initialize the parser represented by <b>Parser</b> to recognize the configuration -- that are specific to the plugins that have been registered so far. -- ------------------------------ procedure Initialize_Parser (App : in out Application'Class; Parser : in out Util.Serialize.IO.Parser'Class) is procedure Process (Module : in out AWA.Modules.Module'Class); procedure Process (Module : in out AWA.Modules.Module'Class) is begin Module.Initialize_Parser (Parser); end Process; begin AWA.Modules.Iterate (App.Modules, Process'Access); end Initialize_Parser; -- ------------------------------ -- Get the current application from the servlet context or service context. -- ------------------------------ function Current return Application_Access is use type AWA.Services.Contexts.Service_Context_Access; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; begin if Ctx /= null then return Ctx.Get_Application; end if; -- If there is no service context, look in the servlet current context. declare use type ASF.Servlets.Servlet_Registry_Access; Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current; begin if Ctx = null then Log.Warn ("There is no service context"); return null; end if; if not (Ctx.all in AWA.Applications.Application'Class) then Log.Warn ("The servlet context is not an application"); return null; end if; return AWA.Applications.Application'Class (Ctx.all)'Access; end; end Current; end AWA.Applications;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with ADO.Drivers; with EL.Contexts.Default; with Util.Files; with Util.Log.Loggers; with ASF.Server; with ASF.Servlets; with AWA.Services.Contexts; with AWA.Components.Factory; with AWA.Applications.Factory; with AWA.Applications.Configs; with AWA.Helpers.Selectors; with AWA.Permissions.Services; with AWA.Permissions.Beans; package body AWA.Applications is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications"); -- ------------------------------ -- Initialize the application -- ------------------------------ overriding procedure Initialize (App : in out Application; Conf : in ASF.Applications.Config; Factory : in out ASF.Applications.Main.Application_Factory'Class) is Ctx : AWA.Services.Contexts.Service_Context; begin Log.Info ("Initializing application"); Ctx.Set_Context (App'Unchecked_Access, null); AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access); ASF.Applications.Main.Application (App).Initialize (Conf, Factory); -- Load the application configuration before any module. Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P)); -- Register the application modules and load their configuration. Application'Class (App).Initialize_Modules; -- Load the plugin application configuration after the module are configured. Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P)); end Initialize; -- ------------------------------ -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. -- ------------------------------ overriding procedure Initialize_Config (App : in out Application; Conf : in out ASF.Applications.Config) is begin Log.Info ("Initializing configuration"); if Conf.Get ("app.modules.dir", "") = "" then Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}"); end if; if Conf.Get ("bundle.dir", "") = "" then Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}"); end if; if Conf.Get ("ado.queries.paths", "") = "" then Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}"); end if; ASF.Applications.Main.Application (App).Initialize_Config (Conf); ADO.Drivers.Initialize (Conf); App.DB_Factory.Create (Conf.Get (P_Database.P)); App.Events.Initialize (App'Unchecked_Access); AWA.Modules.Initialize (App.Modules, Conf); App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean", AWA.Helpers.Selectors.Create_Select_List_Bean'Access); App.Register_Class ("AWA.Permissions.Beans.Permission_Bean", AWA.Permissions.Beans.Create_Permission_Bean'Access); end Initialize_Config; -- ------------------------------ -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. -- ------------------------------ overriding procedure Initialize_Servlets (App : in out Application) is begin Log.Info ("Initializing application servlets"); ASF.Applications.Main.Application (App).Initialize_Servlets; end Initialize_Servlets; -- ------------------------------ -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. -- ------------------------------ overriding procedure Initialize_Filters (App : in out Application) is begin Log.Info ("Initializing application filters"); ASF.Applications.Main.Application (App).Initialize_Filters; end Initialize_Filters; -- ------------------------------ -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. -- ------------------------------ overriding procedure Initialize_Components (App : in out Application) is procedure Register_Functions is new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions); begin Log.Info ("Initializing application components"); ASF.Applications.Main.Application (App).Initialize_Components; App.Add_Components (AWA.Components.Factory.Definition); Register_Functions (App); end Initialize_Components; -- ------------------------------ -- Read the application configuration file <b>awa.xml</b>. This is called after the servlets -- and filters have been registered in the application but before the module registration. -- ------------------------------ procedure Load_Configuration (App : in out Application; Files : in String) is procedure Load_Config (File : in String; Done : out Boolean); Paths : constant String := App.Get_Config (P_Module_Dir.P); Ctx : aliased EL.Contexts.Default.Default_Context; procedure Load_Config (File : in String; Done : out Boolean) is Path : constant String := Util.Files.Find_File_Path (File, Paths); begin Done := False; AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access, True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Application configuration file '{0}' does not exist", Path); end Load_Config; begin Util.Files.Iterate_Path (Files, Load_Config'Access); end Load_Configuration; -- ------------------------------ -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. -- ------------------------------ procedure Initialize_Modules (App : in out Application) is begin null; end Initialize_Modules; -- ------------------------------ -- Start the application. This is called by the server container when the server is started. -- ------------------------------ overriding procedure Start (App : in out Application) is begin -- Start the event service. App.Events.Start; -- Start the application. ASF.Applications.Main.Application (App).Start; -- Dump the route and filters to help in configuration issues. App.Dump_Routes (Util.Log.INFO_LEVEL); end Start; -- ------------------------------ -- Close the application. -- ------------------------------ overriding procedure Close (App : in out Application) is begin App.Events.Stop; ASF.Applications.Main.Application (App).Close; end Close; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in Application_Access; Module : access AWA.Modules.Module'Class; Name : in String; URI : in String := "") is begin App.Register (Module.all'Unchecked_Access, Name, URI); end Register; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (App : Application) return ADO.Sessions.Session is begin return App.DB_Factory.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (App : Application) return ADO.Sessions.Master_Session is begin return App.DB_Factory.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (App : in Application; Name : in String) return AWA.Modules.Module_Access is begin return AWA.Modules.Find_By_Name (App.Modules, Name); end Find_Module; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in AWA.Modules.Module_Access; Name : in String; URI : in String := "") is begin AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI); end Register; -- ------------------------------ -- Send the event in the application event queues. -- ------------------------------ procedure Send_Event (App : in Application; Event : in AWA.Events.Module_Event'Class) is begin App.Events.Send (Event); end Send_Event; -- ------------------------------ -- Execute the <tt>Process</tt> procedure with the event manager used by the application. -- ------------------------------ procedure Do_Event_Manager (App : in out Application; Process : access procedure (Events : in out AWA.Events.Services.Event_Manager)) is begin Process (App.Events); end Do_Event_Manager; -- ------------------------------ -- Initialize the parser represented by <b>Parser</b> to recognize the configuration -- that are specific to the plugins that have been registered so far. -- ------------------------------ procedure Initialize_Parser (App : in out Application'Class; Parser : in out Util.Serialize.IO.Parser'Class) is procedure Process (Module : in out AWA.Modules.Module'Class); procedure Process (Module : in out AWA.Modules.Module'Class) is begin Module.Initialize_Parser (Parser); end Process; begin AWA.Modules.Iterate (App.Modules, Process'Access); end Initialize_Parser; -- ------------------------------ -- Get the current application from the servlet context or service context. -- ------------------------------ function Current return Application_Access is use type AWA.Services.Contexts.Service_Context_Access; Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; begin if Ctx /= null then return Ctx.Get_Application; end if; -- If there is no service context, look in the servlet current context. declare use type ASF.Servlets.Servlet_Registry_Access; Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current; begin if Ctx = null then Log.Warn ("There is no service context"); return null; end if; if not (Ctx.all in AWA.Applications.Application'Class) then Log.Warn ("The servlet context is not an application"); return null; end if; return AWA.Applications.Application'Class (Ctx.all)'Access; end; end Current; end AWA.Applications;
Use the P_Database configuration parameter to configure the database
Use the P_Database configuration parameter to configure the database
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
439f020fd1f8f15dc274878f23a514cb63f14423
src/sqlite/ado-drivers-connections-sqlite.adb
src/sqlite/ado-drivers-connections-sqlite.adb
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 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 Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : Strings.chars_ptr := Strings.New_String (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, SQL_Stat, No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Result := Sqlite3_H.sqlite3_close (Database.Server); Database.Server := System.Null_Address; pragma Unreferenced (Result); end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; DB : Ref.Ref; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is pragma Unreferenced (D); use Strings; use type System.Address; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if not DB.Is_Null then Result := Ref.Create (DB.Value); return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name, Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & To_String (Name) & "=" & Escape (Item); begin Log.Info ("Configure database with {0}", SQL); Database.Execute (SQL); end Configure; begin Database.Server := Handle; Database.Name := Config.Database; DB := Ref.Create (Database.all'Access); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 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 Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.C; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, ADO.C.To_C (SQL_Stat), No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free -- Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Result := Sqlite3_H.sqlite3_close (Database.Server); Database.Server := System.Null_Address; pragma Unreferenced (Result); end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; DB : Ref.Ref; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is pragma Unreferenced (D); use Strings; use type System.Address; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if not DB.Is_Null then Result := Ref.Create (DB.Value); return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name, Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & To_String (Name) & "=" & Escape (Item); begin Log.Info ("Configure database with {0}", SQL); Database.Execute (SQL); end Configure; begin Database.Server := Handle; Database.Name := Config.Database; DB := Ref.Create (Database.all'Access); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
Use ADO.C.String_Ptr type for string->C string management
Use ADO.C.String_Ptr type for string->C string management
Ada
apache-2.0
stcarrez/ada-ado
02d39f085bd57da539512881f86e2128e4cc6757
awa/plugins/awa-comments/src/awa-comments-modules.adb
awa/plugins/awa-comments/src/awa-comments-modules.adb
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with ADO.Sessions.Entities; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- ------------------------------ -- Create a new comment for the associated database entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type)); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; end AWA.Comments.Modules;
----------------------------------------------------------------------- -- awa-comments-module -- Comments module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Log.Loggers; with ADO.Sessions; with ADO.Sessions.Entities; with Security.Permissions; with AWA.Users.Models; with AWA.Permissions; with AWA.Modules.Beans; with AWA.Services.Contexts; with AWA.Comments.Beans; package body AWA.Comments.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module"); package Register is new AWA.Modules.Beans (Module => Comment_Module, Module_Access => Comment_Module_Access); -- ------------------------------ -- Initialize the comments module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Comment_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the comments module"); -- Register the comment list bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_List_Bean", Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access); -- Register the comment bean. Register.Register (Plugin => Plugin, Name => "AWA.Comments.Beans.Comment_Bean", Handler => AWA.Comments.Beans.Create_Comment_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Load the comment identified by the given identifier. -- ------------------------------ procedure Load_Comment (Model : in Comment_Module; Comment : in out AWA.Comments.Models.Comment_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Comment.Load (DB, Id, Found); end Load_Comment; -- ------------------------------ -- Create a new comment for the associated database entity. -- ------------------------------ procedure Create_Comment (Model : in Comment_Module; Permission : in String; Entity_Type : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment.Get_Entity_Id); Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type)); Comment.Set_Author (User); Comment.Set_Create_Date (Ada.Calendar.Clock); Comment.Save (DB); Ctx.Commit; end Create_Comment; -- ------------------------------ -- Update the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. -- ------------------------------ procedure Update_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin if not Comment.Is_Inserted then Log.Error ("The comment was not created"); raise Not_Found with "The comment was not inserted"; end if; Ctx.Start; Log.Info ("Updating the comment {0}", ADO.Identifier'Image (Comment.Get_Id)); -- Check that the user has the update permission on the given comment. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment); Comment.Save (DB); Ctx.Commit; end Update_Comment; -- ------------------------------ -- Delete the comment represented by <tt>Comment</tt> if the current user has the -- permission identified by <tt>Permission</tt>. -- ------------------------------ procedure Delete_Comment (Model : in Comment_Module; Permission : in String; Comment : in out AWA.Comments.Models.Comment_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given answer. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Comment); Comment.Delete (DB); Ctx.Commit; end Delete_Comment; end AWA.Comments.Modules;
Implement the new operation Delete_Comment and Update_Comment
Implement the new operation Delete_Comment and Update_Comment
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
1f1a6e4471bc71664bb09bcf5328ae5996a88b53
src/el-utils.adb
src/el-utils.adb
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Util.Log; use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Loggers.Logger := Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name, Item : in Util.Properties.Value); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then declare Value : constant String := Into.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name, Item : in Util.Properties.Value) is use Ada.Strings; begin if Unbounded.Index (Item, "{") = 0 or Unbounded.Index (Item, "{") = 0 then Log.Debug ("Adding config {0} = {1}", Name, Item); Into.Set (Name, Item); else declare Value : constant Object := Expand (To_String (Item), Local_Context); Val : Unbounded_String; begin if not Util.Beans.Objects.Is_Null (Value) then Val := Util.Beans.Objects.To_Unbounded_String (Value); end if; Log.Debug ("Adding config {0} = {1}", Name, Val); Into.Set (Name, Val); end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- 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.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name : in String; Item : in Util.Beans.Objects.Object); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then declare Value : constant String := Into.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name : in String; Item : in Util.Properties.Value) is use Ada.Strings; Value : constant String := Util.Properties.To_String (Item); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then Log.Debug ("Adding config {0} = {1}", Name, Value); Into.Set_Value (Name, Item); else declare New_Value : constant Object := Expand (Value, Local_Context); begin Log.Debug ("Adding config {0} = {1}", Name, Util.Beans.Objects.To_String (New_Value)); if Util.Beans.Objects.Is_Null (New_Value) then Into.Set (Name, ""); else Into.Set_Value (Name, New_Value); end if; end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
Update the Expand procedure to take into account the new Util.Properties package operations
Update the Expand procedure to take into account the new Util.Properties package operations
Ada
apache-2.0
stcarrez/ada-el
d4e170384c9ee86046c4032fc849f5a9aad90efd
src/util-measures.ads
src/util-measures.ads
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Ada.Containers; with Ada.Finalization; with Util.Streams.Texts; -- = Performance Measurements = -- -- Performance measurements is often made using profiling tools such as GNU gprof or others. -- This profiling is however not always appropriate for production or release delivery. -- The mechanism presented here is a lightweight performance measurement that can be -- used in production systems. -- -- The Ada package `Util.Measures` defines the types and operations to make -- performance measurements. It is designed to be used for production and multi-threaded -- environments. -- -- == Create the measure set == -- -- Measures are collected in a `Measure_Set`. Each measure has a name, a counter and -- a sum of time spent for all the measure. The measure set should be declared as some -- global variable. The implementation is thread safe meaning that a measure set can -- be used by several threads at the same time. It can also be associated with -- a per-thread data (or task attribute). -- -- To declare the measure set, use: -- -- with Util.Measures; -- ... -- Perf : Util.Measures.Measure_Set; -- -- == Measure the implementation == -- -- A measure is made by creating a variable of type `Stamp`. The declaration of -- this variable marks the begining of the measure. The measure ends at the -- next call to the `Report` procedure. -- -- with Util.Measures; -- ... -- declare -- Start : Util.Measures.Stamp; -- begin -- ... -- Util.Measures.Report (Perf, Start, "Measure for a block"); -- end; -- -- When the `Report` procedure is called, the time that elapsed between the creation of -- the `Start` variable and the procedure call is computed. This time is -- then associated with the measure title and the associated counter is incremented. -- The precision of the measured time depends on the system. On GNU/Linux, it uses -- `gettimeofday`. -- -- If the block code is executed several times, the measure set will report -- the number of times it was executed. -- -- == Reporting results == -- -- After measures are collected, the results can be saved in a file or in -- an output stream. When saving the measures, the measure set is cleared. -- -- Util.Measures.Write (Perf, "Title of measures", -- Ada.Text_IO.Standard_Output); -- -- == Measure Overhead == -- -- The overhead introduced by the measurement is quite small as it does not exceeds 1.5 us -- on a 2.6 Ghz Core Quad. -- -- == What must be measured == -- -- Defining a lot of measurements for a production system is in general not very useful. -- Measurements should be relatively high level measurements. For example: -- -- * Loading or saving a file -- * Rendering a page in a web application -- * Executing a database query -- package Util.Measures is type Unit_Type is (Seconds, Milliseconds, Microseconds, Nanoseconds); -- ------------------------------ -- Measure Set -- ------------------------------ -- The measure set represent a collection of measures each of them being -- associated with a same name. Several measure sets can be created to -- collect different kinds of runtime information. The measure set can be -- set on a per-thread data and every call to <b>Report</b> will be -- associated with that measure set. -- -- Measure set are thread-safe. type Measure_Set is limited private; type Measure_Set_Access is access all Measure_Set; -- Disable collecting measures on the measure set. procedure Disable (Measures : in out Measure_Set); -- Enable collecting measures on the measure set. procedure Enable (Measures : in out Measure_Set); -- Set the per-thread measure set. procedure Set_Current (Measures : in Measure_Set_Access); -- Get the per-thread measure set. function Get_Current return Measure_Set_Access; -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class); -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type); -- Dump an XML result with the measures in a file. procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String); -- ------------------------------ -- Stamp -- ------------------------------ -- The stamp marks the beginning of a measure when the variable of such -- type is declared. The measure represents the time that elapsed between -- the stamp creation and when the <b>Report</b> method is called. type Stamp is limited private; -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1); -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1); -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds); private type String_Access is access String; type Stamp is limited record Start : Ada.Calendar.Time := Ada.Calendar.Clock; end record; type Measure; type Measure_Access is access Measure; type Measure is limited record Next : Measure_Access; Time : Duration; Count : Positive; Name : String_Access; end record; type Buckets_Type is array (Ada.Containers.Hash_Type range <>) of Measure_Access; type Buckets_Access is access all Buckets_Type; -- To reduce contention we only protect insertion and updates of measures. -- To write the measure set, we steal the buckets and force the next call -- to <b>Add</b> to reallocate the buckets. protected type Measure_Data is -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time); -- Add the measure procedure Add (Title : in String; D : in Duration; Count : in Positive := 1); private Start : Ada.Calendar.Time := Ada.Calendar.Clock; Buckets : Buckets_Access; end Measure_Data; type Measure_Set is new Ada.Finalization.Limited_Controlled with record Enabled : Boolean := True; pragma Atomic (Enabled); Data : Measure_Data; end record; -- Finalize the measures and release the storage. overriding procedure Finalize (Measures : in out Measure_Set); end Util.Measures;
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Calendar; with Ada.Containers; with Ada.Finalization; with Util.Streams.Texts; -- = Performance Measurements = -- -- Performance measurements is often made using profiling tools such as GNU gprof or others. -- This profiling is however not always appropriate for production or release delivery. -- The mechanism presented here is a lightweight performance measurement that can be -- used in production systems. -- -- The Ada package `Util.Measures` defines the types and operations to make -- performance measurements. It is designed to be used for production and multi-threaded -- environments. -- -- == Create the measure set == -- -- Measures are collected in a `Measure_Set`. Each measure has a name, a counter and -- a sum of time spent for all the measure. The measure set should be declared as some -- global variable. The implementation is thread safe meaning that a measure set can -- be used by several threads at the same time. It can also be associated with -- a per-thread data (or task attribute). -- -- To declare the measure set, use: -- -- with Util.Measures; -- ... -- Perf : Util.Measures.Measure_Set; -- -- == Measure the implementation == -- -- A measure is made by creating a variable of type `Stamp`. The declaration of -- this variable marks the begining of the measure. The measure ends at the -- next call to the `Report` procedure. -- -- with Util.Measures; -- ... -- declare -- Start : Util.Measures.Stamp; -- begin -- ... -- Util.Measures.Report (Perf, Start, "Measure for a block"); -- end; -- -- When the `Report` procedure is called, the time that elapsed between the creation of -- the `Start` variable and the procedure call is computed. This time is -- then associated with the measure title and the associated counter is incremented. -- The precision of the measured time depends on the system. On GNU/Linux, it uses -- `gettimeofday`. -- -- If the block code is executed several times, the measure set will report -- the number of times it was executed. -- -- == Reporting results == -- -- After measures are collected, the results can be saved in a file or in -- an output stream. When saving the measures, the measure set is cleared. -- -- Util.Measures.Write (Perf, "Title of measures", -- Ada.Text_IO.Standard_Output); -- -- == Measure Overhead == -- -- The overhead introduced by the measurement is quite small as it does not exceeds 1.5 us -- on a 2.6 Ghz Core Quad. -- -- == What must be measured == -- -- Defining a lot of measurements for a production system is in general not very useful. -- Measurements should be relatively high level measurements. For example: -- -- * Loading or saving a file -- * Rendering a page in a web application -- * Executing a database query -- package Util.Measures is type Unit_Type is (Seconds, Milliseconds, Microseconds, Nanoseconds); -- ------------------------------ -- Measure Set -- ------------------------------ -- The measure set represent a collection of measures each of them being -- associated with a same name. Several measure sets can be created to -- collect different kinds of runtime information. The measure set can be -- set on a per-thread data and every call to <b>Report</b> will be -- associated with that measure set. -- -- Measure set are thread-safe. type Measure_Set is limited private; type Measure_Set_Access is access all Measure_Set; -- Disable collecting measures on the measure set. procedure Disable (Measures : in out Measure_Set); -- Enable collecting measures on the measure set. procedure Enable (Measures : in out Measure_Set); -- Set the per-thread measure set. procedure Set_Current (Measures : in Measure_Set_Access); -- Get the per-thread measure set. function Get_Current return Measure_Set_Access; -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class); -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type); -- Dump an XML result with the measures in a file. procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String); -- ------------------------------ -- Stamp -- ------------------------------ -- The stamp marks the beginning of a measure when the variable of such -- type is declared. The measure represents the time that elapsed between -- the stamp creation and when the <b>Report</b> method is called. type Stamp is limited private; -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1); -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1); -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds); private type String_Access is access String; type Stamp is limited record Start : Ada.Calendar.Time := Ada.Calendar.Clock; end record; type Measure; type Measure_Access is access Measure; type Measure is limited record Next : Measure_Access; Time : Duration; Count : Positive; Name : String_Access; end record; type Buckets_Type is array (Ada.Containers.Hash_Type range <>) of Measure_Access; type Buckets_Access is access all Buckets_Type; -- To reduce contention we only protect insertion and updates of measures. -- To write the measure set, we steal the buckets and force the next call -- to <b>Add</b> to reallocate the buckets. protected type Measure_Data is -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time); -- Add the measure procedure Add (Title : in String; D : in Duration; Count : in Positive := 1); private Start : Ada.Calendar.Time := Ada.Calendar.Clock; Buckets : Buckets_Access; end Measure_Data; type Measure_Set is new Ada.Finalization.Limited_Controlled with record Enabled : Boolean := True; pragma Atomic (Enabled); Data : Measure_Data; end record; -- Finalize the measures and release the storage. overriding procedure Finalize (Measures : in out Measure_Set); end Util.Measures;
Fix style compilation warning
Fix style compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bfc1c6503fc4323f89944a3ad6e844a4e522560f
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 Gtk.Scrolled_Window; 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 Console.Frame := Frame; 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 Gtk.Cell_Renderer_Text.Gtk_New (Console.Col_Text); 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 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; Scrolled : Gtk.Scrolled_Window.Gtk_Scrolled_Window; begin Gtk.List_Store.Gtk_New (Console.List, Types); Gtk.Scrolled_Window.Gtk_New (Scrolled); Scrolled.Set_Policy (Gtk.Enums.Policy_Always, Gtk.Enums.Policy_Always); 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; Scrolled.Add (Console.Tree); Scrolled.Show_All; Console.Tree.Set_Model (+Console.List); Console.Frame.Add (Scrolled); Console.Frame.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); Console.Scrolled.Set_Policy (Gtk.Enums.Policy_Always, Gtk.Enums.Policy_Always); Console.Frame := Frame; Console.Frame.Add (Console.Scrolled); -- 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 Gtk.Cell_Renderer_Text.Gtk_New (Console.Col_Text); 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 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); 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.Scrolled.Add (Console.Tree); Console.Scrolled.Show_All; Console.Tree.Set_Model (+Console.List); 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;
Create the scrolled window when the console is created
Create the scrolled window when the console is created
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f1da88619e8c28b92a5224f18dd81b9e7304933f
src/util-streams-pipes.adb
src/util-streams-pipes.adb
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Unix based systems -- Copyright (C) 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Pipes is -- ----------------------- -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. -- ----------------------- procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ) is begin Util.Processes.Spawn (Stream.Proc, Command, Mode); end Open; -- ----------------------- -- Close the pipe and wait for the external process to terminate. -- ----------------------- overriding procedure Close (Stream : in out Pipe_Stream) is begin Util.Processes.Wait (Stream.Proc); end Close; -- ----------------------- -- Get the process exit status. -- ----------------------- function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is begin return Util.Processes.Get_Exit_Status (Stream.Proc); end Get_Exit_Status; -- ----------------------- -- Returns True if the process is running. -- ----------------------- function Is_Running (Stream : in Pipe_Stream) return Boolean is begin return Util.Processes.Is_Running (Stream.Proc); end Is_Running; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc); begin if Output = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Output.Write (Buffer); end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Input : constant Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc); begin if Input = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Input.Read (Into, Last); end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Pipe_Stream) is begin null; end Finalize; end Util.Streams.Pipes;
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Unix based systems -- Copyright (C) 2011, 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; package body Util.Streams.Pipes is -- ----------------------- -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. -- ----------------------- procedure Set_Shell (Stream : in out Pipe_Stream; Shell : in String) is begin Util.Processes.Set_Shell (Stream.Proc, Shell); end Set_Shell; -- ----------------------- -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. -- ----------------------- procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ) is begin Util.Processes.Spawn (Stream.Proc, Command, Mode); end Open; -- ----------------------- -- Close the pipe and wait for the external process to terminate. -- ----------------------- overriding procedure Close (Stream : in out Pipe_Stream) is begin Util.Processes.Wait (Stream.Proc); end Close; -- ----------------------- -- Get the process exit status. -- ----------------------- function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is begin return Util.Processes.Get_Exit_Status (Stream.Proc); end Get_Exit_Status; -- ----------------------- -- Returns True if the process is running. -- ----------------------- function Is_Running (Stream : in Pipe_Stream) return Boolean is begin return Util.Processes.Is_Running (Stream.Proc); end Is_Running; -- ----------------------- -- Write the buffer array to the output stream. -- ----------------------- overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc); begin if Output = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Output.Write (Buffer); end Write; -- ----------------------- -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ----------------------- overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Input : constant Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc); begin if Input = null then raise Ada.IO_Exceptions.Status_Error with "Process is not launched"; end if; Input.Read (Into, Last); end Read; -- ----------------------- -- Flush the stream and release the buffer. -- ----------------------- overriding procedure Finalize (Object : in out Pipe_Stream) is begin null; end Finalize; end Util.Streams.Pipes;
Implement Set_Shell procedure
Implement Set_Shell procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
fd35c66524c5ed498aeafc2c89e32c70d6a15401
src/asf-components-html-panels.adb
src/asf-components-html-panels.adb
----------------------------------------------------------------------- -- html.panels -- Layout panels -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package body ASF.Components.Html.Panels is function Get_Layout (UI : UIPanelGroup; Context : in Faces_Context'Class) return String is Value : constant EL.Objects.Object := UI.Get_Attribute (Context, "layout"); Layout : constant String := EL.Objects.To_String (Value); begin if Layout = "div" or Layout = "block" then return "block"; elsif Layout = "none" then return ""; else return "span"; end if; end Get_Layout; procedure Encode_Begin (UI : in UIPanelGroup; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Tag : constant String := UI.Get_Layout (Context); begin if Tag'Length > 0 then Writer.Start_Optional_Element (Tag); end if; end; end Encode_Begin; procedure Encode_End (UI : in UIPanelGroup; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Tag : constant String := UI.Get_Layout (Context); begin if Tag'Length > 0 then Writer.End_Optional_Element (Tag); end if; end; end Encode_End; end ASF.Components.Html.Panels;
----------------------------------------------------------------------- -- html.panels -- Layout panels -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package body ASF.Components.Html.Panels is function Get_Layout (UI : UIPanelGroup; Context : in Faces_Context'Class) return String is Value : constant EL.Objects.Object := UI.Get_Attribute (Context, "layout"); Layout : constant String := EL.Objects.To_String (Value); begin if Layout = "div" or Layout = "block" then return "div"; elsif Layout = "none" then return ""; else return "span"; end if; end Get_Layout; procedure Encode_Begin (UI : in UIPanelGroup; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Tag : constant String := UI.Get_Layout (Context); begin if Tag'Length > 0 then Writer.Start_Optional_Element (Tag); UI.Render_Attributes (Context, Writer); end if; end; end Encode_Begin; procedure Encode_End (UI : in UIPanelGroup; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Tag : constant String := UI.Get_Layout (Context); begin if Tag'Length > 0 then Writer.End_Optional_Element (Tag); end if; end; end Encode_End; end ASF.Components.Html.Panels;
Fix <h:panelGroup> rendering for a div or block layout
Fix <h:panelGroup> rendering for a div or block layout
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
02c007a14f85d1df97b0c0d74cc5acea3a4b977e
src/mysql/ado-schemas-mysql.adb
src/mysql/ado-schemas-mysql.adb
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 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 ADO.Statements; with ADO.Statements.Create; with ADO.SQL; with Ada.Strings.Fixed; package body ADO.Schemas.Mysql 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(11)" then return T_INTEGER; elsif Value = "bigint(20)" then return T_LONG_INTEGER; elsif Value = "tinyint(4)" then return T_TINYINT; elsif Value = "smallint(6)" then return T_SMALLINT; elsif Value = "longblob" 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 = "decimal" 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 ("show full columns from ")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; Query : constant ADO.SQL.Query_Access := Stmt.Get_Query; begin ADO.SQL.Append_Name (Target => Query.SQL, Name => Name); Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (0); 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 (1); Col.Col_Type := String_To_Type (To_String (Value)); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "YES"; 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 ("show tables")); 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.Mysql;
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 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 ADO.Statements; with ADO.Statements.Create; with ADO.SQL; with Ada.Strings.Fixed; package body ADO.Schemas.Mysql 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(11)" then return T_INTEGER; elsif Value = "bigint(20)" then return T_LONG_INTEGER; elsif Value = "tinyint(4)" then return T_TINYINT; elsif Value = "smallint(6)" then return T_SMALLINT; elsif Value = "longblob" 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 = "decimal" 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 ("show full columns from ")); Last : Column_Definition := null; Col : Column_Definition; Value : Unbounded_String; Query : constant ADO.SQL.Query_Access := Stmt.Get_Query; begin ADO.SQL.Append_Name (Target => Query.SQL, Name => Name); Stmt.Execute; while Stmt.Has_Elements loop Col := new Column; Col.Name := Stmt.Get_Unbounded_String (0); if not Stmt.Is_Null (2) then Col.Collation := Stmt.Get_Unbounded_String (2); end if; if not Stmt.Is_Null (5) then Col.Default := Stmt.Get_Unbounded_String (5); end if; if Last /= null then Last.Next_Column := Col; else Table.First_Column := Col; end if; Value := Stmt.Get_Unbounded_String (1); Col.Col_Type := String_To_Type (To_String (Value)); Value := Stmt.Get_Unbounded_String (3); Col.Is_Null := Value = "YES"; 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 ("show tables")); 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.Mysql;
Check for NULL on the collation and default values
Check for NULL on the collation and default values
Ada
apache-2.0
stcarrez/ada-ado
c6175d54cd8082647dcacac291b4a18bcec549f9
src/util-strings-transforms.adb
src/util-strings-transforms.adb
----------------------------------------------------------------------- -- Util-texts -- Various Text Transformation Utilities -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Util.Strings.Transforms is -- ------------------------------ -- Escape the content into the result stream using the JavaScript -- escape rules. -- ------------------------------ function Escape_Javascript (Content : String) return String is Result : Ada.Strings.Unbounded.Unbounded_String; begin TR.Escape_Java_Script (Content, Result); return Ada.Strings.Unbounded.To_String (Result); end Escape_Javascript; -- ------------------------------ -- Escape the content into the result stream using the Java -- escape rules. -- ------------------------------ function Escape_Java (Content : String) return String is Result : Ada.Strings.Unbounded.Unbounded_String; begin TR.Escape_Java (Content, Result); return Ada.Strings.Unbounded.To_String (Result); end Escape_Java; -- ------------------------------ -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 -- ------------------------------ function Escape_Xml (Content : String) return String is Result : Ada.Strings.Unbounded.Unbounded_String; begin TR.Escape_Xml (Content, Result); return Ada.Strings.Unbounded.To_String (Result); end Escape_Xml; end Util.Strings.Transforms;
----------------------------------------------------------------------- -- util-strings-transforms -- Various Text Transformation Utilities -- 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. ----------------------------------------------------------------------- package body Util.Strings.Transforms is -- ------------------------------ -- Escape the content into the result stream using the JavaScript -- escape rules. -- ------------------------------ function Escape_Javascript (Content : String) return String is Result : Ada.Strings.Unbounded.Unbounded_String; begin TR.Escape_Java_Script (Content, Result); return Ada.Strings.Unbounded.To_String (Result); end Escape_Javascript; -- ------------------------------ -- Escape the content into the result stream using the Java -- escape rules. -- ------------------------------ function Escape_Java (Content : String) return String is Result : Ada.Strings.Unbounded.Unbounded_String; begin TR.Escape_Java (Content, Result); return Ada.Strings.Unbounded.To_String (Result); end Escape_Java; -- ------------------------------ -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 -- ------------------------------ function Escape_Xml (Content : String) return String is Result : Ada.Strings.Unbounded.Unbounded_String; begin TR.Escape_Xml (Content, Result); return Ada.Strings.Unbounded.To_String (Result); end Escape_Xml; end Util.Strings.Transforms;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7703cf07e68ccc127dbb885893151a19a5270da0
src/security-policies-roles.adb
src/security-policies-roles.adb
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; -- ------------------------------ -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. -- ------------------------------ procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Find_Role (Role); Into.Count := Into.Count + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Util.Strings.Tokenizers; with Security.Controllers; with Security.Controllers.Roles; package body Security.Policies.Roles is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies.Roles"); -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Data := new Role_Policy_Context; Data.Roles := Roles; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. -- ------------------------------ procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String) is Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME); Data : Role_Policy_Context_Access; Map : Role_Map; begin if Policy = null then Log.Error ("There is no security policy: " & NAME); end if; Role_Policy'Class (Policy.all).Set_Roles (Roles, Map); Data := new Role_Policy_Context; Data.Roles := Map; Context.Set_Policy_Context (Policy, Data.all'Access); end Set_Role_Context; -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Role_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Get the roles that grant the given permission. -- ------------------------------ function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map is begin return Manager.Grants (Permission); end Get_Grants; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; -- ------------------------------ -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. -- ------------------------------ procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map) is procedure Process (Role : in String; Done : out Boolean); procedure Process (Role : in String; Done : out Boolean) is begin Into (Manager.Find_Role (Role)) := True; Done := False; end Process; begin Into := (others => False); Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles, Pattern => ",", Process => Process'Access, Going => Ada.Strings.Forward); end Set_Roles; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Role_Policy'Class; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use Security.Controllers.Roles; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Find_Role (Role); Into.Count := Into.Count + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); Index : Permission_Index; begin Security.Permissions.Add_Permission (Name, Index); for I in 1 .. Into.Count loop Into.Grants (Index) (Into.Roles (I)) := True; end loop; Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Role_Type; begin Into.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Role_Policy'Class, Element_Type_Access => Role_Policy_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. -- ------------------------------ procedure Prepare_Config (Policy : in out Role_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config_Mapper.Set_Context (Reader, Policy'Unchecked_Access); end Prepare_Config; -- ------------------------------ -- Finalize the policy manager. -- ------------------------------ overriding procedure Finalize (Policy : in out Role_Policy) is use type Ada.Strings.Unbounded.String_Access; begin for I in Policy.Names'Range loop exit when Policy.Names (I) = null; Ada.Strings.Unbounded.Free (Policy.Names (I)); end loop; end Finalize; -- ------------------------------ -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. -- ------------------------------ function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access is Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME); begin if Policy = null or else not (Policy.all in Role_Policy'Class) then return null; else return Role_Policy'Class (Policy.all)'Access; end if; end Get_Role_Policy; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Policies.Roles;
Fix Get_Grants definition
Fix Get_Grants definition
Ada
apache-2.0
stcarrez/ada-security
fd3875bb17fd7ccc5a3e8fc919c45edf386517fe
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; 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. -- ------------------------------ procedure Execute (Cmd : in Command; 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 = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; 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. -- ------------------------------ 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|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 GNU license or"); Put_Line (" a proprietary license. The author's name and email addresses"); Put_Line (" 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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. -- ------------------------------ procedure Execute (Cmd : in Command; 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 = "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, 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. -- ------------------------------ 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|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 license 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;
Update for the support of new licenses
Update for the support of new licenses
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
264ce5e9724d4f754a828e9fb8c50126c8d5d86a
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.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. -- ------------------------------ procedure Execute (Cmd : in Command; 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 = "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, 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. -- ------------------------------ 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|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 license 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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. -- ------------------------------ procedure Execute (Cmd : in Command; 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. -- ------------------------------ 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;
Add support for GPL v3 license
Add support for GPL v3 license
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2c0edcb4ab4daaec6cad25f7b78499fc3c66aa43
testutil/util-tests-servers.adb
testutil/util-tests-servers.adb
----------------------------------------------------------------------- -- util-tests-server - A small non-compliant-inefficient HTTP server used for unit tests -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with Ada.Streams; with Util.Streams.Sockets; with Util.Streams.Texts; with Util.Log.Loggers; package body Util.Tests.Servers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Tests.Server"); -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (From : in Server) return Natural is begin return From.Port; end Get_Port; -- ------------------------------ -- Get the server name. -- ------------------------------ function Get_Host (From : in Server) return String is pragma Unreferenced (From); begin return GNAT.Sockets.Host_Name; end Get_Host; -- ------------------------------ -- Start the server task. -- ------------------------------ procedure Start (S : in out Server) is begin S.Server.Start (S'Unchecked_Access); end Start; -- ------------------------------ -- Stop the server task. -- ------------------------------ procedure Stop (S : in out Server) is begin S.Need_Shutdown := True; for I in 1 .. 10 loop delay 0.1; if S.Server'Terminated then return; end if; end loop; abort S.Server; end Stop; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ procedure Process_Line (Into : in out Server; Line : in Ada.Strings.Unbounded.Unbounded_String) is begin null; end Process_Line; task body Server_Task is use GNAT.Sockets; Address : Sock_Addr_Type; Server : Socket_Type; Socket : Socket_Type; Instance : Server_Access := null; Status : Selector_Status; begin Address.Port := 0; Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1); Create_Socket (Server); select accept Start (S : in Server_Access) do Instance := S; Bind_Socket (Server, Address); Address := GNAT.Sockets.Get_Socket_Name (Server); Listen_Socket (Server); Instance.Port := Natural (Address.Port); end Start; or terminate; end select; Log.Info ("Internal HTTP server started at port {0}", Port_Type'Image (Address.Port)); while not Instance.Need_Shutdown loop Accept_Socket (Server, Socket, Address, 1.0, null, Status); if Socket /= No_Socket then Log.Info ("Accepted connection"); declare Stream : aliased Util.Streams.Sockets.Socket_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Stream.Open (Socket); Input.Initialize (From => Stream'Unchecked_Access); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Into => Line, Strip => True); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); Instance.Process_Line (Line); end; end loop; exception when E : others => Log.Error ("Exception: ", E); end; Close_Socket (Socket); end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Server_Task; end Util.Tests.Servers;
----------------------------------------------------------------------- -- util-tests-server - A small non-compliant-inefficient HTTP server used for unit tests -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with Ada.Streams; with Util.Streams.Sockets; with Util.Streams.Texts; with Util.Log.Loggers; package body Util.Tests.Servers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Tests.Server"); -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (From : in Server) return Natural is begin return From.Port; end Get_Port; -- ------------------------------ -- Get the server name. -- ------------------------------ function Get_Host (From : in Server) return String is pragma Unreferenced (From); begin return GNAT.Sockets.Host_Name; end Get_Host; -- ------------------------------ -- Start the server task. -- ------------------------------ procedure Start (S : in out Server) is begin S.Server.Start (S'Unchecked_Access); end Start; -- ------------------------------ -- Stop the server task. -- ------------------------------ procedure Stop (S : in out Server) is begin S.Need_Shutdown := True; for I in 1 .. 10 loop delay 0.1; if S.Server'Terminated then return; end if; end loop; abort S.Server; end Stop; -- ------------------------------ -- Process the line received by the server. -- ------------------------------ procedure Process_Line (Into : in out Server; Line : in Ada.Strings.Unbounded.Unbounded_String) is begin null; end Process_Line; task body Server_Task is use GNAT.Sockets; Address : Sock_Addr_Type; Server : Socket_Type; Socket : Socket_Type; Instance : Server_Access := null; Status : Selector_Status; begin Address.Port := 0; Create_Socket (Server); select accept Start (S : in Server_Access) do Instance := S; Address.Addr := Addresses (Get_Host_By_Name (S.Get_Host), 1); Bind_Socket (Server, Address); Address := GNAT.Sockets.Get_Socket_Name (Server); Listen_Socket (Server); Instance.Port := Natural (Address.Port); end Start; or terminate; end select; Log.Info ("Internal HTTP server started at port {0}", Port_Type'Image (Address.Port)); while not Instance.Need_Shutdown loop Accept_Socket (Server, Socket, Address, 1.0, null, Status); if Socket /= No_Socket then Log.Info ("Accepted connection"); declare Stream : aliased Util.Streams.Sockets.Socket_Stream; Input : Util.Streams.Texts.Reader_Stream; begin Stream.Open (Socket); Input.Initialize (From => Stream'Unchecked_Access); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Input.Read_Line (Into => Line, Strip => True); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); Instance.Process_Line (Line); end; end loop; exception when E : others => Log.Error ("Exception: ", E); end; Close_Socket (Socket); end if; end loop; GNAT.Sockets.Close_Socket (Server); exception when E : others => Log.Error ("Exception", E); end Server_Task; end Util.Tests.Servers;
Use Get_Host function to find the server host name
Use Get_Host function to find the server host name
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
712fafdf2c9649c312b0400b6e3a0aa47c6052e7
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; limited with Security.Controllers; limited with Security.Contexts; -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- package Security.Permissions is -- EL function name exposed by Set_Functions. HAS_PERMISSION_FN : constant String := "hasPermission"; -- URI for the EL functions exposed by the security package (See Set_Functions). AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth"; Invalid_Name : exception; type Security_Context_Access is access all Contexts.Security_Context'Class; type Permission_Index is new Natural; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Abstract_Permission is abstract tagged limited null record; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; 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 Role_Type) return Boolean is abstract; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; -- ------------------------------ -- Permission -- ------------------------------ -- Represents a permission for a given role. type Permission (Role : Permission_Type) is new Abstract_Permission with null record; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Abstract_Permission with record URI : String (1 .. Len); end record; -- ------------------------------ -- File Permission -- ------------------------------ type File_Mode is (READ, WRITE); -- Represents a permission to access a given file. type File_Permission (Len : Natural; Mode : File_Mode) is new Abstract_Permission with record Path : String (1 .. Len); end record; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Permission_Manager is new Ada.Finalization.Limited_Controlled with private; type Permission_Manager_Access is access all Permission_Manager'Class; procedure Add_Permission (Manager : in out Permission_Manager; Name : in String; Permission : in Controller_Access); -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Permission_Manager; Name : in String) return Role_Type; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in Permission_Manager; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Returns True if the user has the given role permission. function Has_Permission (Manager : in Permission_Manager; User : in Principal'Class; Permission : in Permission_Type) return Boolean; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Permission_Manager'Class; Index : in Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Get the role name. function Get_Role_Name (Manager : in Permission_Manager; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Permission_Manager; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Permission_Manager; Name : in String; Result : out Role_Type); -- 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 Permission_Manager; URI : in String; To : in String); -- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b> -- permissions. procedure Grant_File_Permission (Manager : in out Permission_Manager; Path : in String; To : in String); -- Read the policy file procedure Read_Policy (Manager : in out Permission_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Permission_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Permission_Manager); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Permission_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Security.Permissions.Permission_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; -- Register a set of functions in the namespace -- xmlns:fn="http://code.google.com/p/ada-asf/auth" -- Functions: -- hasPermission(NAME) -- Returns True if the permission NAME is granted -- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); private use Util.Strings; type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permission_Index; -- 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; -- No rule -- No_Rule : constant Access_Rule := (Count => 0, -- Permissions => (others => Permission_Index'First)); -- 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 Permission_Manager; 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 Permission_Manager is new Ada.Finalization.Limited_Controlled with record Names : Role_Name_Array; Cache : Rules_Ref_Access; Next_Role : Role_Type := Role_Type'First; Policies : Policy_Vector.Vector; Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; end record; -- EL function to check if the given permission name is granted by the current -- security context. function Has_Permission (Value : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; limited with Security.Controllers; limited with Security.Contexts; -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- package Security.Permissions is -- EL function name exposed by Set_Functions. HAS_PERMISSION_FN : constant String := "hasPermission"; -- URI for the EL functions exposed by the security package (See Set_Functions). AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth"; Invalid_Name : exception; type Security_Context_Access is access all Contexts.Security_Context'Class; type Permission_Index is new Natural; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Abstract_Permission is abstract tagged limited null record; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; type Role_Type_Array is array (Positive range <>) of Role_Type; -- The <b>Role_Map</b> represents a set of roles which are assigned to a user. -- Each role is represented by a boolean in the map. The implementation is limited -- to 64 roles (the number of different permissions can be higher). type Role_Map is array (Role_Type'Range) of Boolean; pragma Pack (Role_Map); -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); -- ------------------------------ -- Permission -- ------------------------------ -- Represents a permission for a given role. type Permission (Role : Permission_Type) is new Abstract_Permission with null record; -- ------------------------------ -- URI Permission -- ------------------------------ -- Represents a permission to access a given URI. type URI_Permission (Len : Natural) is new Abstract_Permission with record URI : String (1 .. Len); end record; -- ------------------------------ -- File Permission -- ------------------------------ type File_Mode is (READ, WRITE); -- Represents a permission to access a given file. type File_Permission (Len : Natural; Mode : File_Mode) is new Abstract_Permission with record Path : String (1 .. Len); end record; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Permission_Manager is new Ada.Finalization.Limited_Controlled with private; type Permission_Manager_Access is access all Permission_Manager'Class; procedure Add_Permission (Manager : in out Permission_Manager; Name : in String; Permission : in Controller_Access); -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Permission_Manager; Name : in String) return Role_Type; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in Permission_Manager; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean; -- Returns True if the user has the given role permission. function Has_Permission (Manager : in Permission_Manager; User : in Principal'Class; Permission : in Permission_Type) return Boolean; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Permission_Manager'Class; Index : in Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Get the role name. function Get_Role_Name (Manager : in Permission_Manager; Role : in Role_Type) return String; -- Create a role procedure Create_Role (Manager : in out Permission_Manager; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Permission_Manager; Name : in String; Result : out Role_Type); -- 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 Permission_Manager; URI : in String; To : in String); -- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b> -- permissions. procedure Grant_File_Permission (Manager : in out Permission_Manager; Path : in String; To : in String); -- Read the policy file procedure Read_Policy (Manager : in out Permission_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Permission_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Permission_Manager); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Permission_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Security.Permissions.Permission_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; -- Register a set of functions in the namespace -- xmlns:fn="http://code.google.com/p/ada-asf/auth" -- Functions: -- hasPermission(NAME) -- Returns True if the permission NAME is granted -- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); private use Util.Strings; type Role_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permission_Index; -- 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; -- No rule -- No_Rule : constant Access_Rule := (Count => 0, -- Permissions => (others => Permission_Index'First)); -- 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 Permission_Manager; 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 Permission_Manager is new Ada.Finalization.Limited_Controlled with record Names : Role_Name_Array; Cache : Rules_Ref_Access; Next_Role : Role_Type := Role_Type'First; Policies : Policy_Vector.Vector; Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; end record; -- EL function to check if the given permission name is granted by the current -- security context. function Has_Permission (Value : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; end Security.Permissions;
Remove the Principal
Remove the Principal
Ada
apache-2.0
Letractively/ada-security
169da02389b3856c05695eecb704cdc047f7b23e
src/postgresql/ado-postgresql.adb
src/postgresql/ado-postgresql.adb
----------------------------------------------------------------------- -- ado-postgresql -- PostgreSQL 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.Postgresql; package body ADO.Postgresql 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.Postgresql.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.Postgresql.Initialize; end Initialize; end ADO.Postgresql;
----------------------------------------------------------------------- -- ado-postgresql -- PostgreSQL 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.Postgresql; package body ADO.Postgresql is -- ------------------------------ -- Initialize the Postgresql driver. -- ------------------------------ procedure Initialize is begin ADO.Connections.Postgresql.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); ADO.Connections.Postgresql.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.Postgresql.Initialize; end Initialize; end ADO.Postgresql;
Implement the Initialize procedure and use it
Implement the Initialize procedure and use it
Ada
apache-2.0
stcarrez/ada-ado
451641d38f4b495cd68dac4d6834b34d7f6f68d5
regtests/util-processes-tests.adb
regtests/util-processes-tests.adb
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- 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.Log.Loggers; with Util.Test_Caller; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; package body Util.Processes.Tests is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\sc\sd\se\sf\stest_marker\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; package body Util.Processes.Tests is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (null, P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Buffered_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (null, Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; end Util.Processes.Tests;
Fix regular expression to verify the process output on Windows (CR + LF issue)
Fix regular expression to verify the process output on Windows (CR + LF issue)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f0c6f97abb9ebbdd0ddb9edf1829263ce6c4c9ff
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_START_CODE, L_END_CODE); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
Add L_START_CODE and L_END_CODE line types
Add L_START_CODE and L_END_CODE line types
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
5a3c4563c64c8e2cb8b1f8491514a085c264cb27
mat/src/mat-consoles.adb
mat/src/mat-consoles.adb
----------------------------------------------------------------------- -- mat-consoles - 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. ----------------------------------------------------------------------- with Util.Strings; with MAT.Formats; package body MAT.Consoles is -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Formats.Addr (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Formats.Addr (From); To_Value : constant String := MAT.Formats.Addr (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Formats.Duration (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Util.Strings.Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - 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. ----------------------------------------------------------------------- with Util.Strings; with MAT.Formats; package body MAT.Consoles is -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Formats.Addr (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the address range and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) is From_Value : constant String := MAT.Formats.Addr (From); To_Value : constant String := MAT.Formats.Addr (To); begin Console_Type'Class (Console).Print_Field (Field, From_Value & "-" & To_Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Formats.Size (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Formats.Duration (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Util.Strings.Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; end MAT.Consoles;
Use MAT.Formats.Size to format a size
Use MAT.Formats.Size to format a size
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b41df89ce493bf0fe5a6b427c9feee9f22712b4f
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.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 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;
----------------------------------------------------------------------- -- 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.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 -- Check that the user has the vote permission on the given object. AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission), Entity => Id); 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); -- 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 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;
Check the permission before writing any log since we may not have any user
Check the permission before writing any log since we may not have any user
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8e697b16589dc71a82951bd19e41ca9c5a4a74b3
awa/src/awa-events-queues-persistents.adb
awa/src/awa-events-queues-persistents.adb
----------------------------------------------------------------------- -- awa-events-queues-persistents -- AWA Event Queues -- 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.Calendar; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Serialize.IO.XML; with Util.Properties; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.Tools; with AWA.Services.Contexts; with AWA.Users.Models; with ADO; with ADO.Queries; with ADO.Sessions; with ADO.SQL; package body AWA.Events.Queues.Persistents is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents"); -- ------------------------------ -- Get the queue name. -- ------------------------------ overriding function Get_Name (From : in Persistent_Queue) return String is begin return From.Name; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ overriding function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is begin return From.Queue; end Get_Queue; -- ------------------------------ -- Queue the event. The event is saved in the database with a relation to -- the user, the user session, the event queue and the event type. -- ------------------------------ overriding procedure Enqueue (Into : in out Persistent_Queue; Event : in AWA.Events.Module_Event'Class) is use Ada.Strings.Unbounded; use Util.Streams; procedure Add_Property (Name, Value : in Util.Properties.Value); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; Has_Param : Boolean := False; Output : Util.Serialize.IO.XML.Output_Stream; procedure Add_Property (Name, Value : in Util.Properties.Value) is begin if not Has_Param then Output.Initialize (Size => 10000); Has_Param := True; Output.Start_Entity (Name => "params"); end if; Output.Start_Entity (Name => "param"); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_String (Value => To_String (Value)); Output.End_Entity (Name => "param"); end Add_Property; begin Ctx.Start; Msg.Set_Queue (Into.Queue); Msg.Set_User (Ctx.Get_User); Msg.Set_Session (Ctx.Get_User_Session); Msg.Set_Create_Date (Event.Get_Time); Msg.Set_Status (AWA.Events.Models.QUEUED); -- Collect the event parameters in a string and format the result in XML. -- If there is no parameter, avoid the overhead of allocating and formatting this. Event.Props.Iterate (Process => Add_Property'Access); if Has_Param then Output.End_Entity (Name => "params"); Msg.Set_Parameters (Util.Streams.Texts.To_String (Buffered.Buffered_Stream (Output))); end if; -- Msg.Set_Message_Type Msg.Save (DB); Ctx.Commit; Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id)); end Enqueue; overriding procedure Dequeue (From : in out Persistent_Queue; Process : access procedure (Event : in Module_Event'Class)) is package AC renames AWA.Services.Contexts; -- Prepare the message by indicating in the database it is going to be processed -- by the given server and task. procedure Prepare_Message (Msg : in out Models.Message_Ref); -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref); -- Finish processing the message by marking it as being processed. procedure Finish_Message (Msg : in out Models.Message_Ref); Ctx : constant AC.Service_Context_Access := AC.Current; DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Messages : Models.Message_Vector; Query : ADO.Queries.Context; Task_Id : Integer := 0; -- ------------------------------ -- Prepare the message by indicating in the database it is going to be processed -- by the given server and task. -- ------------------------------ procedure Prepare_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSING); Msg.Set_Server_Id (From.Server_Id); Msg.Set_Task_Id (Task_Id); Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Prepare_Message; -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref) is User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User; Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session; Event : Module_Event; begin Process (Event); end Dispatch_Message; -- ------------------------------ -- Finish processing the message by marking it as being processed. -- ------------------------------ procedure Finish_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSED); Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Finish_Message; Count : Natural; begin Ctx.Start; Query.Set_Query (Models.Query_Queue_Pending_Message); Query.Bind_Param ("queue", From.Queue.Get_Id); Query.Bind_Param ("max", From.Max_Batch); Models.List (Messages, DB, Query); Count := Natural (Messages.Length); -- Prepare the event messages by marking them in the database. -- This makes sure that no other server or task (if any), will process them. if Count > 0 then for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Prepare_Message'Access); end loop; end if; Ctx.Commit; if Count = 0 then return; end if; -- Dispatch each event. for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Dispatch_Message'Access); end loop; -- After having dispatched the events, mark them as dispatched in the queue. Ctx.Start; for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Finish_Message'Access); end loop; Ctx.Commit; end Dequeue; -- ------------------------------ -- Create the queue associated with the given name and configure it by using -- the configuration properties. -- ------------------------------ function Create_Queue (Name : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Access is package AC renames AWA.Services.Contexts; Ctx : constant AC.Service_Context_Access := AC.Current; Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Queue : AWA.Events.Models.Queue_Ref; Query : ADO.SQL.Query; Found : Boolean; begin Session.Begin_Transaction; -- Find the queue instance which matches the name. Query.Set_Filter ("o.name = ?"); Query.Add_Param (Name); Queue.Find (Session => Session, Query => Query, Found => Found); -- But create the queue instance if it does not exist. if not Found then Log.Info ("Creating database queue {0}", Name); Queue.Set_Name (Name); Queue.Save (Session); else Log.Info ("Using database queue {0}", Name); end if; Session.Commit; declare Result : constant Persistent_Queue_Access := new Persistent_Queue '(Name_Length => Name'Length, Name => Name, Queue => Queue, others => <>); begin return Result.all'Access; end; end Create_Queue; end AWA.Events.Queues.Persistents;
----------------------------------------------------------------------- -- awa-events-queues-persistents -- AWA Event Queues -- 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.Calendar; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Serialize.Tools; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Applications; with AWA.Events.Services; with ADO; with ADO.Queries; with ADO.Sessions; with ADO.SQL; package body AWA.Events.Queues.Persistents is package AC renames AWA.Services.Contexts; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents"); -- ------------------------------ -- Get the queue name. -- ------------------------------ overriding function Get_Name (From : in Persistent_Queue) return String is begin return From.Name; end Get_Name; -- ------------------------------ -- Get the model queue reference object. -- Returns a null object if the queue is not persistent. -- ------------------------------ overriding function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is begin return From.Queue; end Get_Queue; -- ------------------------------ -- Queue the event. The event is saved in the database with a relation to -- the user, the user session, the event queue and the event type. -- ------------------------------ overriding procedure Enqueue (Into : in out Persistent_Queue; Event : in AWA.Events.Module_Event'Class) is procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager); Ctx : constant AC.Service_Context_Access := AC.Current; App : constant AWA.Applications.Application_Access := Ctx.Get_Application; DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Msg : AWA.Events.Models.Message_Ref; procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is begin Manager.Set_Message_Type (Msg, Event.Get_Event_Kind); end Set_Event; begin App.Do_Event_Manager (Set_Event'Access); Ctx.Start; Msg.Set_Queue (Into.Queue); Msg.Set_User (Ctx.Get_User); Msg.Set_Session (Ctx.Get_User_Session); Msg.Set_Create_Date (Event.Get_Time); Msg.Set_Status (AWA.Events.Models.QUEUED); -- Collect the event parameters in a string and format the result in JSON. Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props)); Msg.Save (DB); Ctx.Commit; Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id)); end Enqueue; overriding procedure Dequeue (From : in out Persistent_Queue; Process : access procedure (Event : in Module_Event'Class)) is -- Prepare the message by indicating in the database it is going to be processed -- by the given server and task. procedure Prepare_Message (Msg : in out Models.Message_Ref); -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref); -- Finish processing the message by marking it as being processed. procedure Finish_Message (Msg : in out Models.Message_Ref); Ctx : constant AC.Service_Context_Access := AC.Current; DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Messages : Models.Message_Vector; Query : ADO.Queries.Context; Task_Id : Integer := 0; -- ------------------------------ -- Prepare the message by indicating in the database it is going to be processed -- by the given server and task. -- ------------------------------ procedure Prepare_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSING); Msg.Set_Server_Id (From.Server_Id); Msg.Set_Task_Id (Task_Id); Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Prepare_Message; -- Dispatch the event. procedure Dispatch_Message (Msg : in out Models.Message_Ref) is User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User; Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session; Event : Module_Event; begin Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Msg.Get_Message_Type.Get_Name)); Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props); Process (Event); exception when E : others => Log.Error ("Exception when processing event", E, True); end Dispatch_Message; -- ------------------------------ -- Finish processing the message by marking it as being processed. -- ------------------------------ procedure Finish_Message (Msg : in out Models.Message_Ref) is begin Msg.Set_Status (Models.PROCESSED); Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Msg.Save (DB); end Finish_Message; Count : Natural; begin Ctx.Start; Query.Set_Query (Models.Query_Queue_Pending_Message); Query.Bind_Param ("queue", From.Queue.Get_Id); Query.Bind_Param ("max", From.Max_Batch); Models.List (Messages, DB, Query); Count := Natural (Messages.Length); -- Prepare the event messages by marking them in the database. -- This makes sure that no other server or task (if any), will process them. if Count > 0 then for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Prepare_Message'Access); end loop; end if; Ctx.Commit; if Count = 0 then return; end if; -- Dispatch each event. for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Dispatch_Message'Access); end loop; -- After having dispatched the events, mark them as dispatched in the queue. Ctx.Start; for I in 0 .. Count - 1 loop Messages.Update_Element (Index => I, Process => Finish_Message'Access); end loop; Ctx.Commit; end Dequeue; -- ------------------------------ -- Create the queue associated with the given name and configure it by using -- the configuration properties. -- ------------------------------ function Create_Queue (Name : in String; Props : in EL.Beans.Param_Vectors.Vector; Context : in EL.Contexts.ELContext'Class) return Queue_Access is package AC renames AWA.Services.Contexts; Ctx : constant AC.Service_Context_Access := AC.Current; Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx); Queue : AWA.Events.Models.Queue_Ref; Query : ADO.SQL.Query; Found : Boolean; begin Session.Begin_Transaction; -- Find the queue instance which matches the name. Query.Set_Filter ("o.name = ?"); Query.Add_Param (Name); Queue.Find (Session => Session, Query => Query, Found => Found); -- But create the queue instance if it does not exist. if not Found then Log.Info ("Creating database queue {0}", Name); Queue.Set_Name (Name); Queue.Save (Session); else Log.Info ("Using database queue {0}", Name); end if; Session.Commit; declare Result : constant Persistent_Queue_Access := new Persistent_Queue '(Name_Length => Name'Length, Name => Name, Queue => Queue, others => <>); begin return Result.all'Access; end; end Create_Queue; end AWA.Events.Queues.Persistents;
Save the event properties using a JSON formatter Restore the event properties after loading the event message from database
Save the event properties using a JSON formatter Restore the event properties after loading the event message from database
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
c92e63e64f939df8be50ec44e6c9de0b319fe421
tools/druss-commands-bboxes.adb
tools/druss-commands-bboxes.adb
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Streams; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with Druss.Config; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); procedure Discover (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Discover; -- Add the bbox with the given IP address. procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP); begin if not Gw.Is_Null then Log.Debug ("Bbox {0} is already registered", IP); return; end if; Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a new bbox at {0}", IP); Gw := Druss.Gateways.Gateway_Refs.Create; Gw.Value.IP := Ada.Strings.Unbounded.To_Unbounded_String (IP); Context.Gateways.Append (Gw); end if; exception when E : others => null; end Add_Bbox; procedure Discover (Command : in Command_Type; Context : in out Context_Type) is Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Check_Bbox (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Check_Bbox; procedure Process (URI : in String) is Pos : Natural; begin if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then return; end if; Pos := Util.Strings.Index (URI, ':', 6); if Pos > 0 then Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context); -- Check_Bbox (); end if; end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; Druss.Config.Save_Gateways (Context.Gateways); end Discover; -- ------------------------------ -- Set the password to be used by the Bbox API to connect to the box. -- ------------------------------ procedure Password (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count < 2 then Druss.Commands.Driver.Usage (Args); end if; declare Passwd : constant String := Args.Get_Argument (2); Gw : Druss.Gateways.Gateway_Ref; procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd); end Change_Password; begin if Args.Get_Count = 2 then Druss.Gateways.Iterate (Context.Gateways, Change_Password'Access); else for I in 3 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Change_Password (Gw.Value.all); end if; end loop; end if; Druss.Config.Save_Gateways (Context.Gateways); end; end Password; -- ------------------------------ -- Execute the command with the arguments. The command name is passed with the command -- arguments. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover (Context); elsif Args.Get_Argument (1) = "password" then Command.Password (Args, Context); else Put_Line ("Invalid sub-command: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Manage and define the configuration to connect to the Bbox"); Put_Line ("Usage: bbox <operation>..."); New_Line; Put_Line (" Druss needs to know the list of Bboxes which are available on the network."); Put_Line (" It also need some credentials to connect to the Bbox using the Bbox API."); Put_Line (" The 'bbox' command allows to manage that list and configuration."); Put_Line (" Examples:"); Put_Line (" bbox discover Discover the bbox(es) connected to the LAN"); Put_Line (" bbox add IP Add a bbox knowing its IP address"); Put_Line (" bbox del IP Delete a bbox from the list"); Put_Line (" bbox password <pass> [IP] Set the bbox API connection password"); end Help; end Druss.Commands.Bboxes;
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with Druss.Config; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); procedure Discover (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Discover; -- Add the bbox with the given IP address. procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP); begin if not Gw.Is_Null then Log.Debug ("Bbox {0} is already registered", IP); return; end if; Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a new bbox at {0}", IP); Gw := Druss.Gateways.Gateway_Refs.Create; Gw.Value.IP := Ada.Strings.Unbounded.To_Unbounded_String (IP); Context.Gateways.Append (Gw); end if; exception when E : others => null; end Add_Bbox; procedure Discover (Command : in Command_Type; Context : in out Context_Type) is Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Check_Bbox (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Check_Bbox; procedure Process (URI : in String) is Pos : Natural; begin if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then return; end if; Pos := Util.Strings.Index (URI, ':', 6); if Pos > 0 then Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context); -- Check_Bbox (); end if; end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; Druss.Config.Save_Gateways (Context.Gateways); end Discover; -- ------------------------------ -- Set the password to be used by the Bbox API to connect to the box. -- ------------------------------ procedure Password (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count < 2 then Druss.Commands.Driver.Usage (Args); end if; declare Passwd : constant String := Args.Get_Argument (2); Gw : Druss.Gateways.Gateway_Ref; procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type) is begin Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd); end Change_Password; begin if Args.Get_Count = 2 then Druss.Gateways.Iterate (Context.Gateways, Change_Password'Access); else for I in 3 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Change_Password (Gw.Value.all); end if; end loop; end if; Druss.Config.Save_Gateways (Context.Gateways); end; end Password; -- ------------------------------ -- Execute the command with the arguments. The command name is passed with the command -- arguments. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover (Context); elsif Args.Get_Argument (1) = "password" then Command.Password (Args, Context); else Put_Line ("Invalid sub-command: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Manage and define the configuration to connect to the Bbox"); Put_Line ("Usage: bbox <operation>..."); New_Line; Put_Line (" Druss needs to know the list of Bboxes which are available on the network."); Put_Line (" It also need some credentials to connect to the Bbox using the Bbox API."); Put_Line (" The 'bbox' command allows to manage that list and configuration."); Put_Line (" Examples:"); Put_Line (" bbox discover Discover the bbox(es) connected to the LAN"); Put_Line (" bbox add IP Add a bbox knowing its IP address"); Put_Line (" bbox del IP Delete a bbox from the list"); Put_Line (" bbox password <pass> [IP] Set the bbox API connection password"); end Help; end Druss.Commands.Bboxes;
Add with clause Ada.Strings.Unbounded
Add with clause Ada.Strings.Unbounded
Ada
apache-2.0
stcarrez/bbox-ada-api
2e3b6130861f769c27980d7121facfb90ae13a25
awa/src/awa-components-wikis.adb
awa/src/awa-components-wikis.adb
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Documents; with Wiki.Parsers; with Wiki.Helpers; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Html; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then return Wiki.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.SYNTAX_CREOLE; elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; else return Wiki.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Get the links renderer that must be used to render image and page links. -- ------------------------------ function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Get the plugin factory that must be used by the Wiki parser. -- ------------------------------ function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Wiki.Plugins.Plugin_Factory'Class) then return null; else return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access; end if; end Get_Plugin_Factory; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Links.Link_Renderer_Access; use type Wiki.Plugins.Plugin_Factory_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Plugins := UI.Get_Plugin_Factory (Context); if Plugins /= null then Engine.Set_Plugin_Factory (Plugins); end if; Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_Wide_Wide_String (Value), Doc); Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Render (Doc); end if; Writer.End_Element ("div"); end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is begin if Wiki.Helpers.Is_Url (Link) then URI := To_Unbounded_Wide_Wide_String (Link); else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Documents; with Wiki.Parsers; with Wiki.Helpers; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Filters.TOC; with Wiki.Streams.Html; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Streams.Html.Html_Output_Stream with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Raw (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Wiki.Strings.WString) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Wiki_Syntax is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" or Format = "FORMAT_DOTCLEAR" then return Wiki.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.SYNTAX_GOOGLE; elsif Format = "phpbb" or Format = "FORMAT_PHPBB" then return Wiki.SYNTAX_PHPBB; elsif Format = "creole" or Format = "FORMAT_CREOLE" then return Wiki.SYNTAX_CREOLE; elsif Format = "mediawiki" or Format = "FORMAT_MEDIAWIKI" then return Wiki.SYNTAX_MEDIA_WIKI; else return Wiki.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Get the links renderer that must be used to render image and page links. -- ------------------------------ function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Links.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Get the plugin factory that must be used by the Wiki parser. -- ------------------------------ function Get_Plugin_Factory (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Plugins.Plugin_Factory_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, PLUGINS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Wiki.Plugins.Plugin_Factory'Class) then return null; else return Wiki.Plugins.Plugin_Factory'Class (Bean.all)'Access; end if; end Get_Plugin_Factory; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Links.Link_Renderer_Access; use type Wiki.Plugins.Plugin_Factory_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Doc : Wiki.Documents.Document; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Format : constant Wiki.Wiki_Syntax := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Links.Link_Renderer_Access; Plugins : Wiki.Plugins.Plugin_Factory_Access; Engine : Wiki.Parsers.Parser; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Plugins := UI.Get_Plugin_Factory (Context); if Plugins /= null then Engine.Set_Plugin_Factory (Plugins); end if; Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Format); Engine.Parse (Util.Beans.Objects.To_Wide_Wide_String (Value), Doc); Renderer.Set_Output_Stream (Html'Unchecked_Access); Renderer.Render (Doc); end if; Writer.End_Element ("div"); end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Link_Renderer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = IMAGE_PREFIX_ATTR then From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); elsif Name = PAGE_PREFIX_ATTR then From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value); end if; end Set_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is begin if Wiki.Helpers.Is_Url (Link) then URI := To_Unbounded_Wide_Wide_String (Link); else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in Link_Renderer_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
Fix the name of the attribute to get the wiki plugins factory
Fix the name of the attribute to get the wiki plugins factory
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b5c71e17614abc0a4c8013f27a592390f8ff7d94
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Make the Policy type abstract and the Get_Name function abstract
Make the Policy type abstract and the Get_Name function abstract
Ada
apache-2.0
Letractively/ada-security
afef33d942e1d476d56e52735ef51e477282eee7
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; Is_Hidden : Boolean; begin Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then Controller.Log_URI := To_Unbounded_String (URI (URI'First .. Pos)); while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); Append (Controller.Log_URI, URI (Pos + 1 .. Pos2)); Is_Hidden := URI (Pos + 1 .. Pos2 - 1) = "password"; if Is_Hidden then Append (Controller.Log_URI, "XXXXXXX"); end if; if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); if not Is_Hidden then Append (Controller.Log_URI, URI (Pos2 + 1 .. Next - 1)); end if; Append (Controller.Log_URI, "&"); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); if not Is_Hidden then Append (Controller.Log_URI, URI (Pos2 + 1 .. URI'Last)); end if; Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Append (Controller.Log_URI, URI (Pos + 1 .. URI'Last)); Pos := URI'Last; end if; end loop; else Controller.Log_URI := Controller.URI; end if; Log.Info ("Set connection URI: {0}", Controller.Log_URI); end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Controller : in out Configuration; Database : in String) is begin Controller.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Get the database driver name. -- ------------------------------ function Get_Driver (Controller : in Configuration) return String is begin if Controller.Driver /= null then return Get_Driver_Name (Controller.Driver.all); else return ""; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.Log_URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); if Result.Is_Null then Log.Error ("Driver {0} failed to create connection {0}", Config.Driver.Name.all, To_String (Config.Log_URI)); raise Connection_Error with "Data source is not initialized: driver error"; end if; Log.Info ("Created connection to '{0}' -> {1}", Config.Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.Log_URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; Is_Hidden : Boolean; begin Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then Controller.Log_URI := To_Unbounded_String (URI (URI'First .. Pos)); while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); Append (Controller.Log_URI, URI (Pos + 1 .. Pos2)); Is_Hidden := URI (Pos + 1 .. Pos2 - 1) = "password"; if Is_Hidden then Append (Controller.Log_URI, "XXXXXXX"); end if; if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); if not Is_Hidden then Append (Controller.Log_URI, URI (Pos2 + 1 .. Next - 1)); end if; Append (Controller.Log_URI, "&"); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); if not Is_Hidden then Append (Controller.Log_URI, URI (Pos2 + 1 .. URI'Last)); end if; Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Append (Controller.Log_URI, URI (Pos + 1 .. URI'Last)); Pos := URI'Last; end if; end loop; else Controller.Log_URI := Controller.URI; end if; Log.Info ("Set connection URI: {0}", Controller.Log_URI); end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Controller : in out Configuration; Database : in String) is begin Controller.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Get the database driver name. -- ------------------------------ function Get_Driver (Controller : in Configuration) return String is begin if Controller.Driver /= null then return Get_Driver_Name (Controller.Driver.all); else return ""; end if; end Get_Driver; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.Log_URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); if Result.Is_Null then Log.Error ("Driver {0} failed to create connection {0}", Config.Driver.Name.all, To_String (Config.Log_URI)); raise Connection_Error with "Data source is not initialized: driver error"; end if; Log.Info ("Created connection to '{0}' -> {1}", Config.Log_URI, Result.Value.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.Log_URI); raise; end Create_Connection; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is Driver : constant ADO.Drivers.Connections.Driver_Access := Database_Connection'Class (Database).Get_Driver; begin return Driver.Get_Driver_Index; end Get_Driver_Index; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 2 loop if Retry = 1 then ADO.Drivers.Initialize; elsif Retry = 2 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Implement the Get_Driver_Index function
Implement the Get_Driver_Index function
Ada
apache-2.0
stcarrez/ada-ado
a057f964760caea845436d52faa087ad0680e098
src/ado-drivers-connections.adb
src/ado-drivers-connections.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Systems.DLLs; with System; with Ada.Strings.Fixed; with Ada.Containers.Doubly_Linked_Lists; with Ada.Exceptions; package body ADO.Drivers.Connections is use Ada.Strings.Fixed; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections"); -- Load the database driver. procedure Load_Driver (Name : in String); -- ------------------------------ -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. -- ------------------------------ procedure Set_Connection (Controller : in out Configuration; URI : in String) is Pos, Pos2, Slash_Pos, Next : Natural; begin Log.Info ("Set connection URI: {0}", URI); Controller.URI := To_Unbounded_String (URI); Pos := Index (URI, "://"); if Pos <= 1 then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid URI: '" & URI & "'"; end if; Controller.Driver := Get_Driver (URI (URI'First .. Pos - 1)); if Controller.Driver = null then Log.Error ("No driver found for connection URI: {0}", URI); raise Connection_Error with "Driver '" & URI (URI'First .. Pos - 1) & "' not found"; end if; Pos := Pos + 3; Slash_Pos := Index (URI, "/", Pos); if Slash_Pos < Pos then Log.Error ("Invalid connection URI: {0}", URI); raise Connection_Error with "Invalid connection URI: '" & URI & "'"; end if; -- Extract the server and port. Pos2 := Index (URI, ":", Pos); if Pos2 >= Pos then Controller.Server := To_Unbounded_String (URI (Pos .. Pos2 - 1)); begin Controller.Port := Natural'Value (URI (Pos2 + 1 .. Slash_Pos - 1)); exception when Constraint_Error => Log.Error ("Invalid port in connection URI: {0}", URI); raise Connection_Error with "Invalid port in connection URI: '" & URI & "'"; end; else Controller.Port := 0; Controller.Server := To_Unbounded_String (URI (Pos .. Slash_Pos - 1)); end if; -- Extract the database name. Pos := Index (URI, "?", Slash_Pos); if Pos - 1 > Slash_Pos + 1 then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. Pos - 1)); elsif Pos = 0 and Slash_Pos + 1 < URI'Last then Controller.Database := To_Unbounded_String (URI (Slash_Pos + 1 .. URI'Last)); else Controller.Database := Null_Unbounded_String; end if; -- Parse the optional properties if Pos > Slash_Pos then while Pos < URI'Last loop Pos2 := Index (URI, "=", Pos + 1); if Pos2 > Pos then Next := Index (URI, "&", Pos2 + 1); if Next > 0 then Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. Next - 1)); Pos := Next; else Controller.Properties.Set (URI (Pos + 1 .. Pos2 - 1), URI (Pos2 + 1 .. URI'Last)); Pos := URI'Last; end if; else Controller.Properties.Set (URI (Pos + 1 .. URI'Last), ""); Pos := URI'Last; end if; end loop; end if; end Set_Connection; -- ------------------------------ -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. -- ------------------------------ procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String) is begin Controller.Properties.Set (Name, Value); end Set_Property; -- ------------------------------ -- Get a property from the datasource configuration. -- If the property does not exist, an empty string is returned. -- ------------------------------ function Get_Property (Controller : in Configuration; Name : in String) return String is begin return Controller.Properties.Get (Name, ""); end Get_Property; -- ------------------------------ -- Get the server hostname. -- ------------------------------ function Get_Server (Controller : in Configuration) return String is begin return To_String (Controller.Server); end Get_Server; -- ------------------------------ -- Set the server hostname. -- ------------------------------ procedure Set_Server (Controller : in out Configuration; Server : in String) is begin Controller.Server := To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Set the server port. -- ------------------------------ procedure Set_Port (Controller : in out Configuration; Port : in Natural) is begin Controller.Port := Port; end Set_Port; -- ------------------------------ -- Get the server port. -- ------------------------------ function Get_Port (Controller : in Configuration) return Natural is begin return Controller.Port; end Get_Port; -- ------------------------------ -- Set the database name. -- ------------------------------ procedure Set_Database (Controller : in out Configuration; Database : in String) is begin Controller.Database := To_Unbounded_String (Database); end Set_Database; -- ------------------------------ -- Get the database name. -- ------------------------------ function Get_Database (Controller : in Configuration) return String is begin return To_String (Controller.Database); end Get_Database; -- ------------------------------ -- Create a new connection using the configuration parameters. -- ------------------------------ procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access) is begin if Config.Driver = null then Log.Error ("No driver found for connection {0}", To_String (Config.URI)); raise Connection_Error with "Data source is not initialized: driver not found"; end if; Config.Driver.Create_Connection (Config, Result); Log.Info ("Created connection to '{0}' -> {1}", Config.URI, Result.Ident); exception when others => Log.Info ("Failed to create connection to '{0}'", Config.URI); raise; end Create_Connection; package Driver_List is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access); Next_Index : Driver_Index := 1; Drivers : Driver_List.List; -- ------------------------------ -- Get the driver unique index. -- ------------------------------ function Get_Driver_Index (D : in Driver) return Driver_Index is begin return D.Index; end Get_Driver_Index; -- ------------------------------ -- Get the driver name. -- ------------------------------ function Get_Driver_Name (D : in Driver) return String is begin return D.Name.all; end Get_Driver_Name; -- ------------------------------ -- Register a database driver. -- ------------------------------ procedure Register (Driver : in Driver_Access) is begin Log.Info ("Register driver {0}", Driver.Name.all); Driver_List.Prepend (Container => Drivers, New_Item => Driver); Driver.Index := Next_Index; Next_Index := Next_Index + 1; end Register; -- ------------------------------ -- Load the database driver. -- ------------------------------ procedure Load_Driver (Name : in String) is Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension; Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize"; Handle : Util.Systems.DLLs.Handle; Addr : System.Address; begin Log.Info ("Loading driver {0}", Lib); Handle := Util.Systems.DLLs.Load (Lib); Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol); declare procedure Init; pragma Import (C, Init); for Init'Address use Addr; begin Init; end; exception when Util.Systems.DLLs.Not_Found => Log.Error ("Driver for {0} was loaded but does not define the initialization symbol", Name); when E : Util.Systems.DLLs.Load_Error => Log.Error ("Driver for {0} was not found: {1}", Name, Ada.Exceptions.Exception_Message (E)); end Load_Driver; -- ------------------------------ -- Get a database driver given its name. -- ------------------------------ function Get_Driver (Name : in String) return Driver_Access is begin Log.Info ("Get driver {0}", Name); for Retry in 0 .. 1 loop if Retry > 0 then Load_Driver (Name); end if; declare Iter : Driver_List.Cursor := Driver_List.First (Drivers); begin while Driver_List.Has_Element (Iter) loop declare D : constant Driver_Access := Driver_List.Element (Iter); begin if Name = D.Name.all then return D; end if; end; Driver_List.Next (Iter); end loop; end; end loop; return null; end Get_Driver; end ADO.Drivers.Connections;
Implement the Set_Database procedure
Implement the Set_Database procedure
Ada
apache-2.0
stcarrez/ada-ado
1f7335f62f125a1951dbe360a08bcc48b9a9aac8
bsp-examples/evb1000/dw1000-bsp.adb
bsp-examples/evb1000/dw1000-bsp.adb
------------------------------------------------------------------------------- -- Copyright (c) 2016 Daniel King -- -- 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 Interfaces; use Interfaces; with STM32.AFIO; with STM32.EXTI; with STM32.GPIO; with STM32.NVIC; with STM32.RCC; with STM32.SPI; package body DW1000.BSP with SPARK_Mode => Off is procedure Select_Device is begin STM32.GPIO.GPIOA_Periph.BSRR.BR := STM32.GPIO.BSRR_BR_Field'(As_Array => True, Arr => (4 => 1, others => 0)); end Select_Device; procedure Deselect_Device is begin STM32.GPIO.GPIOA_Periph.BSRR.BS := STM32.GPIO.BSRR_BS_Field'(As_Array => True, Arr => (4 => 1, others => 0)); end Deselect_Device; procedure Reset_DW1000 is begin -- Configure RSTn GPIO as output STM32.GPIO.GPIOA_Periph.CRL.MODE0 := 2#11#; -- Output 50 MHz STM32.GPIO.GPIOA_Periph.CRL.CNF0 := 2#00#; -- Output push-pull -- Drive the RSTn line low STM32.GPIO.GPIOA_Periph.BSRR.BR := STM32.GPIO.BSRR_BR_Field'(As_Array => True, Arr => (1 => 1, others => 0)); -- Put the RSTn line to hi-Z STM32.GPIO.GPIOA_Periph.CRL.MODE0 := 2#00#; -- Input STM32.GPIO.GPIOA_Periph.CRL.CNF0 := 2#01#; -- Floating input end Reset_DW1000; procedure Acknowledge_DW1000_IRQ is begin STM32.EXTI.EXTI_Periph.PR.PR.Arr (5) := 1; end Acknowledge_DW1000_IRQ; procedure Disable_DW1000_IRQ is begin -- Disable IRQ #25 (EXTI9_5_Interrupt) STM32.NVIC.NVIC_Periph.ICER0 := 16#0200_0000#; end Disable_DW1000_IRQ; procedure Enable_DW1000_IRQ is begin -- Enable IRQ #25 (EXTI9_5_Interrupt) STM32.NVIC.NVIC_Periph.ISER0 := 16#0200_0000#; end Enable_DW1000_IRQ; procedure Use_Slow_SPI_Clock is begin -- Use /32 prescaler (72 MHz / 32 = 2.25 MHz clock) STM32.SPI.SPI1_Periph.CR1.BR := 2#100#; end Use_Slow_SPI_Clock; procedure Use_Fast_SPI_Clock is begin -- Use /4 prescaler (72 MHz / 4 = 18 MHz clock) STM32.SPI.SPI1_Periph.CR1.BR := 2#001#; end Use_Fast_SPI_Clock; procedure Write_Transaction(Header : in DW1000.Types.Byte_Array; Data : in DW1000.Types.Byte_Array) is use type STM32.Bit; begin Select_Device; -- Send header for I in Header'Range loop STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Header (I) ); loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; end loop; -- Send data for I in Data'Range loop loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Data (I) ); end loop; -- Wait for the last byte to finish transmitting. loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; Deselect_Device; end Write_Transaction; procedure Read_Transaction(Header : in DW1000.Types.Byte_Array; Data : out DW1000.Types.Byte_Array) is use type STM32.Bit; begin Disable_DW1000_IRQ; Select_Device; -- Send header for I in Header'Range loop STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Header (I)); loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; end loop; loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; -- Read data for I in Data'Range loop -- Send a dummy byte to begin the transfer STM32.SPI.SPI1_Periph.DR.DR := 16#0000#; loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; Data (I) := Unsigned_8 (STM32.SPI.SPI1_Periph.DR.DR and 16#FF#); end loop; Deselect_Device; Enable_DW1000_IRQ; end Read_Transaction; begin -- Enable peripheral clocks STM32.RCC.RCC_Periph.APB2ENR.SPI1EN := 1; STM32.RCC.RCC_Periph.APB2ENR.AFIOEN := 1; STM32.RCC.RCC_Periph.APB2ENR.IOPAEN := 1; STM32.RCC.RCC_Periph.APB2ENR.IOPBEN := 1; -- Configure GPIO STM32.GPIO.GPIOA_Periph.CRL.MODE4 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.MODE5 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.MODE6 := 2#00#; STM32.GPIO.GPIOA_Periph.CRL.MODE7 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.CNF4 := 2#00#; STM32.GPIO.GPIOA_Periph.CRL.CNF5 := 2#10#; STM32.GPIO.GPIOA_Periph.CRL.CNF6 := 2#10#; STM32.GPIO.GPIOA_Periph.CRL.CNF7 := 2#10#; Deselect_Device; Reset_DW1000; -- Configure SPI STM32.SPI.SPI1_Periph.CR1 := STM32.SPI.CR1_Register'(CPHA => 0, CPOL => 0, MSTR => 1, BR => 2#100#, -- /32 prescaler SPE => 0, LSBFIRST => 0, -- MSB first SSI => 1, SSM => 1, RXONLY => 0, -- Full duplex DFF => 0, -- 8-bit data CRCNEXT => 0, CRCEN => 0, -- No CRC BIDIOE => 0, BIDIMODE => 0, -- Bidirectional Reserved_16_31 => 0); STM32.SPI.SPI1_Periph.CRCPR.CRCPOLY := 7; STM32.SPI.SPI1_Periph.CR1.SPE := 1; -- Configure IRQ STM32.GPIO.GPIOB_Periph.CRL.CNF5 := 2#10#; -- Input with pull-up/down STM32.GPIO.GPIOB_Periph.CRL.MODE5 := 2#00#; -- Input mode STM32.GPIO.GPIOB_Periph.BRR.BR.Arr (5) := 1; -- Pull-down STM32.AFIO.AFIO_Periph.EXTICR2.EXTI.Arr (5) := 2#0001#; -- GPIOB STM32.EXTI.EXTI_Periph.IMR.MR.Arr (5) := 1; -- Enable interrupt STM32.EXTI.EXTI_Periph.EMR.MR.Arr (5) := 0; STM32.EXTI.EXTI_Periph.RTSR.TR.Arr (5) := 1; -- Rising edge enabled STM32.EXTI.EXTI_Periph.FTSR.TR.Arr (5) := 0; -- Falling edge disabled end DW1000.BSP;
------------------------------------------------------------------------------- -- Copyright (c) 2016 Daniel King -- -- 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 Interfaces; use Interfaces; with STM32.AFIO; with STM32.EXTI; with STM32.GPIO; with STM32.NVIC; with STM32.RCC; with STM32.SPI; package body DW1000.BSP with SPARK_Mode => Off is procedure Select_Device is begin STM32.GPIO.GPIOA_Periph.BSRR.BR := STM32.GPIO.BSRR_BR_Field'(As_Array => True, Arr => (4 => 1, others => 0)); end Select_Device; procedure Deselect_Device is begin STM32.GPIO.GPIOA_Periph.BSRR.BS := STM32.GPIO.BSRR_BS_Field'(As_Array => True, Arr => (4 => 1, others => 0)); end Deselect_Device; procedure Reset_DW1000 is begin -- Configure RSTn GPIO as output STM32.GPIO.GPIOA_Periph.CRL.MODE0 := 2#11#; -- Output 50 MHz STM32.GPIO.GPIOA_Periph.CRL.CNF0 := 2#00#; -- Output push-pull -- Drive the RSTn line low STM32.GPIO.GPIOA_Periph.BSRR.BR := STM32.GPIO.BSRR_BR_Field'(As_Array => True, Arr => (1 => 1, others => 0)); -- Put the RSTn line to hi-Z STM32.GPIO.GPIOA_Periph.CRL.MODE0 := 2#00#; -- Input STM32.GPIO.GPIOA_Periph.CRL.CNF0 := 2#01#; -- Floating input end Reset_DW1000; procedure Acknowledge_DW1000_IRQ is begin STM32.EXTI.EXTI_Periph.PR.PR.Arr (5) := 1; end Acknowledge_DW1000_IRQ; procedure Disable_DW1000_IRQ is begin -- Disable IRQ #25 (EXTI9_5_Interrupt) STM32.NVIC.NVIC_Periph.ICER0 := 16#0200_0000#; end Disable_DW1000_IRQ; procedure Enable_DW1000_IRQ is begin -- Enable IRQ #25 (EXTI9_5_Interrupt) STM32.NVIC.NVIC_Periph.ISER0 := 16#0200_0000#; end Enable_DW1000_IRQ; procedure Use_Slow_SPI_Clock is begin -- Use /32 prescaler (72 MHz / 32 = 2.25 MHz clock) STM32.SPI.SPI1_Periph.CR1.BR := 2#100#; end Use_Slow_SPI_Clock; procedure Use_Fast_SPI_Clock is begin -- Use /4 prescaler (72 MHz / 4 = 18 MHz clock) STM32.SPI.SPI1_Periph.CR1.BR := 2#001#; end Use_Fast_SPI_Clock; procedure Write_Transaction(Header : in DW1000.Types.Byte_Array; Data : in DW1000.Types.Byte_Array) is use type STM32.Bit; begin Disable_DW1000_IRQ; Select_Device; -- Send header for I in Header'Range loop STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Header (I) ); loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; end loop; -- Send data for I in Data'Range loop loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Data (I) ); end loop; -- Wait for the last byte to finish transmitting. loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; Deselect_Device; Enable_DW1000_IRQ; end Write_Transaction; procedure Read_Transaction(Header : in DW1000.Types.Byte_Array; Data : out DW1000.Types.Byte_Array) is use type STM32.Bit; begin Disable_DW1000_IRQ; Select_Device; -- Send header for I in Header'Range loop STM32.SPI.SPI1_Periph.DR.DR := Unsigned_16 (Header (I)); loop exit when STM32.SPI.SPI1_Periph.SR.TXE = 1; end loop; end loop; loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; -- Read data for I in Data'Range loop -- Send a dummy byte to begin the transfer STM32.SPI.SPI1_Periph.DR.DR := 16#0000#; loop exit when STM32.SPI.SPI1_Periph.SR.BSY = 0; end loop; Data (I) := Unsigned_8 (STM32.SPI.SPI1_Periph.DR.DR and 16#FF#); end loop; Deselect_Device; Enable_DW1000_IRQ; end Read_Transaction; begin -- Enable peripheral clocks STM32.RCC.RCC_Periph.APB2ENR.SPI1EN := 1; STM32.RCC.RCC_Periph.APB2ENR.AFIOEN := 1; STM32.RCC.RCC_Periph.APB2ENR.IOPAEN := 1; STM32.RCC.RCC_Periph.APB2ENR.IOPBEN := 1; -- Configure GPIO STM32.GPIO.GPIOA_Periph.CRL.MODE4 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.MODE5 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.MODE6 := 2#00#; STM32.GPIO.GPIOA_Periph.CRL.MODE7 := 2#11#; STM32.GPIO.GPIOA_Periph.CRL.CNF4 := 2#00#; STM32.GPIO.GPIOA_Periph.CRL.CNF5 := 2#10#; STM32.GPIO.GPIOA_Periph.CRL.CNF6 := 2#10#; STM32.GPIO.GPIOA_Periph.CRL.CNF7 := 2#10#; Deselect_Device; Reset_DW1000; -- Configure SPI STM32.SPI.SPI1_Periph.CR1 := STM32.SPI.CR1_Register'(CPHA => 0, CPOL => 0, MSTR => 1, BR => 2#100#, -- /32 prescaler SPE => 0, LSBFIRST => 0, -- MSB first SSI => 1, SSM => 1, RXONLY => 0, -- Full duplex DFF => 0, -- 8-bit data CRCNEXT => 0, CRCEN => 0, -- No CRC BIDIOE => 0, BIDIMODE => 0, -- Bidirectional Reserved_16_31 => 0); STM32.SPI.SPI1_Periph.CRCPR.CRCPOLY := 7; STM32.SPI.SPI1_Periph.CR1.SPE := 1; -- Configure IRQ STM32.GPIO.GPIOB_Periph.CRL.CNF5 := 2#10#; -- Input with pull-up/down STM32.GPIO.GPIOB_Periph.CRL.MODE5 := 2#00#; -- Input mode STM32.GPIO.GPIOB_Periph.BRR.BR.Arr (5) := 1; -- Pull-down STM32.AFIO.AFIO_Periph.EXTICR2.EXTI.Arr (5) := 2#0001#; -- GPIOB STM32.EXTI.EXTI_Periph.IMR.MR.Arr (5) := 1; -- Enable interrupt STM32.EXTI.EXTI_Periph.EMR.MR.Arr (5) := 0; STM32.EXTI.EXTI_Periph.RTSR.TR.Arr (5) := 1; -- Rising edge enabled STM32.EXTI.EXTI_Periph.FTSR.TR.Arr (5) := 0; -- Falling edge disabled end DW1000.BSP;
Add missing DW1000 IRQ disable in the Write_Transaction procedure.
Add missing DW1000 IRQ disable in the Write_Transaction procedure. The DW1000 IRQ is disabled during the SPI transactions to prevent a race condition on the SPI if the IRQ handler code accesses the SPI bus during its execution.
Ada
mit
damaki/DW1000
1b105a5e742f5e8825bad80bbc52cf012757b796
awa/plugins/awa-questions/src/awa-questions-modules.adb
awa/plugins/awa-questions/src/awa-questions-modules.adb
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Characters.Conversions; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Wikis.Parsers; with AWA.Wikis.Writers; with ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Questions.Beans; with AWA.Applications; package body AWA.Questions.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module"); package Register is new AWA.Modules.Beans (Module => Question_Module, Module_Access => Question_Module_Access); -- ------------------------------ -- Initialize the questions module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the questions module"); -- Setup the resource bundles. App.Register ("questionMsg", "questions"); -- Edit and save a question. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Bean", Handler => AWA.Questions.Beans.Create_Question_Bean'Access); -- Edit and save an answer. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Answer_Bean", Handler => AWA.Questions.Beans.Create_Answer_Bean'Access); -- List of questions. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_List_Bean", Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access); -- Display a question with its answers. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Display_Bean", Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the questions module. -- ------------------------------ function Get_Question_Module return Question_Module_Access is function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME); begin return Get; end Get_Question_Module; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); WS : AWA.Workspaces.Models.Workspace_Ref; begin Ctx.Start; if Question.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id)); WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace); else Log.Info ("Creating new question {0}", String '(Question.Get_Title)); AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission, Entity => WS); Question.Set_Workspace (WS); Question.Set_Author (User); end if; declare Text : constant String := AWA.Wikis.Writers.To_Text (To_Wide (Question.Get_Description), AWA.Wikis.Parsers.SYNTAX_MIX); Last : Natural; begin if Text'Length < SHORT_DESCRIPTION_LENGTH then Last := Text'Last; else Last := SHORT_DESCRIPTION_LENGTH; end if; Question.Set_Short_Description (Text (Text'First .. Last) & "..."); end; if not Question.Is_Inserted then Question.Set_Create_Date (Ada.Calendar.Clock); else Question.Set_Edit_Date (Ada.Calendar.Clock); end if; Question.Save (DB); Ctx.Commit; end Save_Question; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given question. AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission, Entity => Question); -- Before deleting the question, delete the associated answers. declare Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE); begin Stmt.Set_Filter (Filter => "question_id = ?"); Stmt.Add_Param (Value => Question); Stmt.Execute; end; Question.Delete (DB); Ctx.Commit; end Delete_Question; -- ------------------------------ -- Load the question. -- ------------------------------ procedure Load_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Question.Load (DB, Id, Found); end Load_Question; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save_Answer (Model : in Question_Module; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; if Answer.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id)); else Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission, Entity => Question); Answer.Set_Author (User); end if; if not Answer.Is_Inserted then Answer.Set_Create_Date (Ada.Calendar.Clock); Answer.Set_Question (Question); else Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Answer.Save (DB); Ctx.Commit; end Save_Answer; -- ------------------------------ -- Delete the answer. -- ------------------------------ procedure Delete_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given answer. AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission, Entity => Answer); Answer.Delete (DB); Ctx.Commit; end Delete_Answer; -- ------------------------------ -- Load the answer. -- ------------------------------ procedure Load_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Answer.Load (DB, Id, Found); Question := Answer.Get_Question; end Load_Answer; end AWA.Questions.Modules;
----------------------------------------------------------------------- -- awa-questions-modules -- Module questions -- Copyright (C) 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Characters.Conversions; with AWA.Permissions; with AWA.Services.Contexts; with AWA.Users.Models; with AWA.Workspaces.Models; with AWA.Workspaces.Modules; with AWA.Wikis.Parsers; with AWA.Wikis.Writers; with ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Questions.Beans; with AWA.Applications; package body AWA.Questions.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Questions.Module"); package Register is new AWA.Modules.Beans (Module => Question_Module, Module_Access => Question_Module_Access); -- ------------------------------ -- Initialize the questions module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Question_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the questions module"); -- Setup the resource bundles. App.Register ("questionMsg", "questions"); -- Edit and save a question. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Bean", Handler => AWA.Questions.Beans.Create_Question_Bean'Access); -- Edit and save an answer. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Answer_Bean", Handler => AWA.Questions.Beans.Create_Answer_Bean'Access); -- List of questions. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_List_Bean", Handler => AWA.Questions.Beans.Create_Question_List_Bean'Access); -- Display a question with its answers. Register.Register (Plugin => Plugin, Name => "AWA.Questions.Beans.Question_Display_Bean", Handler => AWA.Questions.Beans.Create_Question_Display_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); end Initialize; -- ------------------------------ -- Get the questions module. -- ------------------------------ function Get_Question_Module return Question_Module_Access is function Get is new AWA.Modules.Get (Question_Module, Question_Module_Access, NAME); begin return Get; end Get_Question_Module; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); function To_Wide (Item : in String) return Wide_Wide_String renames Ada.Characters.Conversions.To_Wide_Wide_String; Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); WS : AWA.Workspaces.Models.Workspace_Ref; begin Ctx.Start; if Question.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Question.Get_Id)); WS := AWA.Workspaces.Models.Workspace_Ref (Question.Get_Workspace); else Log.Info ("Creating new question {0}", String '(Question.Get_Title)); AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Questions.Permission, Entity => WS); Question.Set_Workspace (WS); Question.Set_Author (User); end if; declare Text : constant String := AWA.Wikis.Writers.To_Text (To_Wide (Question.Get_Description), AWA.Wikis.Parsers.SYNTAX_MIX); Last : Natural; begin if Text'Length < SHORT_DESCRIPTION_LENGTH then Last := Text'Last; else Last := SHORT_DESCRIPTION_LENGTH; end if; Question.Set_Short_Description (Text (Text'First .. Last) & "..."); end; if not Question.Is_Inserted then Question.Set_Create_Date (Ada.Calendar.Clock); else Question.Set_Edit_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); end if; Question.Save (DB); Ctx.Commit; end Save_Question; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given question. AWA.Permissions.Check (Permission => ACL_Delete_Questions.Permission, Entity => Question); -- Before deleting the question, delete the associated answers. declare Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Questions.Models.ANSWER_TABLE); begin Stmt.Set_Filter (Filter => "question_id = ?"); Stmt.Add_Param (Value => Question); Stmt.Execute; end; Question.Delete (DB); Ctx.Commit; end Delete_Question; -- ------------------------------ -- Load the question. -- ------------------------------ procedure Load_Question (Model : in Question_Module; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Question.Load (DB, Id, Found); end Load_Question; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save_Answer (Model : in Question_Module; Question : in AWA.Questions.Models.Question_Ref'Class; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; if Answer.Is_Inserted then Log.Info ("Updating question {0}", ADO.Identifier'Image (Answer.Get_Id)); else Log.Info ("Creating new answer for {0}", ADO.Identifier'Image (Question.Get_Id)); -- Check that the user has the create permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Answer_Questions.Permission, Entity => Question); Answer.Set_Author (User); end if; if not Answer.Is_Inserted then Answer.Set_Create_Date (Ada.Calendar.Clock); Answer.Set_Question (Question); else Answer.Set_Edit_Date (ADO.Nullable_Time '(Value => Ada.Calendar.Clock, Is_Null => False)); end if; Answer.Save (DB); Ctx.Commit; end Save_Answer; -- ------------------------------ -- Delete the answer. -- ------------------------------ procedure Delete_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); begin Ctx.Start; -- Check that the user has the delete permission on the given answer. AWA.Permissions.Check (Permission => ACL_Delete_Answer.Permission, Entity => Answer); Answer.Delete (DB); Ctx.Commit; end Delete_Answer; -- ------------------------------ -- Load the answer. -- ------------------------------ procedure Load_Answer (Model : in Question_Module; Answer : in out AWA.Questions.Models.Answer_Ref'Class; Question : in out AWA.Questions.Models.Question_Ref'Class; Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx); Found : Boolean; begin Answer.Load (DB, Id, Found); Question := Answer.Get_Question; end Load_Answer; end AWA.Questions.Modules;
Fix setting the question edit date to use the Nullable_Time type
Fix setting the question edit date to use the Nullable_Time type
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
baf93030b811a5bb8b931c5845fb2d65dc9eb338
src/ado-schemas-entities.ads
src/ado-schemas-entities.ads
----------------------------------------------------------------------- -- ado-schemas-entities -- Entity types cache -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with ADO.Sessions; package ADO.Schemas.Entities is No_Entity_Type : exception; -- The entity cache maintains a static cache of database entities. type Entity_Cache is private; -- Find the entity type index associated with the given database table. -- Raises the No_Entity_Type exception if no such mapping exist. function Find_Entity_Type (Cache : in Entity_Cache; Table : in Class_Mapping_Access) return ADO.Entity_Type; -- Find the entity type index associated with the given database table. -- Raises the No_Entity_Type exception if no such mapping exist. function Find_Entity_Type (Cache : in Entity_Cache; Name : in Util.Strings.Name_Access) return ADO.Entity_Type; -- Initialize the entity cache by reading the database entity table. procedure Initialize (Cache : in out Entity_Cache; Session : in out ADO.Sessions.Session'Class); private package Entity_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => ADO.Entity_Type, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Entity_Cache is record Entities : Entity_Map.Map; end record; end ADO.Schemas.Entities;
----------------------------------------------------------------------- -- ado-schemas-entities -- Entity types cache -- 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.Containers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with ADO.Sessions; with ADO.Parameters; package ADO.Schemas.Entities is No_Entity_Type : exception; -- The entity cache maintains a static cache of database entities. type Entity_Cache is new ADO.Caches.Cache_Type with private; -- Expand the name into a target parameter value to be used in the SQL query. -- The Expander can return a T_NULL when a value is not found or -- it may also raise some exception. overriding function Expand (Instance : in out Entity_Cache; Name : in String) return ADO.Parameters.Parameter; -- Find the entity type index associated with the given database table. -- Raises the No_Entity_Type exception if no such mapping exist. function Find_Entity_Type (Cache : in Entity_Cache; Table : in Class_Mapping_Access) return ADO.Entity_Type; -- Find the entity type index associated with the given database table. -- Raises the No_Entity_Type exception if no such mapping exist. function Find_Entity_Type (Cache : in Entity_Cache; Name : in Util.Strings.Name_Access) return ADO.Entity_Type; -- Initialize the entity cache by reading the database entity table. procedure Initialize (Cache : in out Entity_Cache; Session : in out ADO.Sessions.Session'Class); private package Entity_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => ADO.Entity_Type, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); type Entity_Cache is new ADO.Caches.Cache_Type with record Entities : Entity_Map.Map; end record; end ADO.Schemas.Entities;
Update the Entity_Cache so that it inherit from ADO.Caches.Cache_Type type Override the Expand function
Update the Entity_Cache so that it inherit from ADO.Caches.Cache_Type type Override the Expand function
Ada
apache-2.0
stcarrez/ada-ado
2046005b7b0375f1e6674ffdba288e24118689e4
src/orka/implementation/orka-resources-textures-ktx.adb
src/orka/implementation/orka-resources-textures-ktx.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System; with Ada.Exceptions; with Ada.Real_Time; with Ada.Unchecked_Deallocation; with GL.Low_Level.Enums; with GL.Types; with GL.Pixels.Queries; with Orka.Jobs; with Orka.Logging; with Orka.KTX; package body Orka.Resources.Textures.KTX is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; package Messages is new Orka.Logging.Messages (Resource_Loader); type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record Data : Loaders.Resource_Data; Manager : Managers.Manager_Ptr; end record; overriding procedure Execute (Object : KTX_Load_Job; Context : Jobs.Execution_Context'Class); ----------------------------------------------------------------------------- use all type Ada.Real_Time.Time; function Read_Texture (Bytes : Byte_Array_Pointers.Constant_Reference; Path : String; Start : Ada.Real_Time.Time) return GL.Objects.Textures.Texture is T1 : Ada.Real_Time.Time renames Start; T2 : constant Ada.Real_Time.Time := Clock; use Ada.Streams; use GL.Low_Level.Enums; use type GL.Types.Size; T3, T4, T5, T6 : Ada.Real_Time.Time; begin if not Orka.KTX.Valid_Identifier (Bytes) then raise Texture_Load_Error with Path & " is not a KTX file"; end if; declare Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes); Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels); Texture : GL.Objects.Textures.Texture (Header.Kind); Width : constant GL.Types.Size := Header.Width; Height : GL.Types.Size := Header.Height; Depth : GL.Types.Size := Header.Depth; begin T3 := Clock; -- Allocate storage case Header.Kind is when Texture_2D_Array => Depth := Header.Array_Elements; when Texture_1D_Array => Height := Header.Array_Elements; pragma Assert (Depth = 0); when Texture_Cube_Map_Array => -- For a cube map array, depth is the number of layer-faces Depth := Header.Array_Elements * 6; when Texture_3D => null; when Texture_2D | Texture_Cube_Map => pragma Assert (Depth = 0); when Texture_1D => if Header.Compressed then raise Texture_Load_Error with Path & " has unknown 1D compressed format"; end if; pragma Assert (Height = 0); pragma Assert (Depth = 0); when others => raise Program_Error; end case; if Header.Compressed then Texture.Allocate_Storage (Levels, 1, Header.Compressed_Format, Width, Height, Depth); else Texture.Allocate_Storage (Levels, 1, Header.Internal_Format, Width, Height, Depth); end if; case Header.Kind is when Texture_1D => Height := 1; Depth := 1; when Texture_1D_Array | Texture_2D => Depth := 1; when Texture_2D_Array | Texture_3D => null; when Texture_Cube_Map | Texture_Cube_Map_Array => -- Texture_Cube_Map uses 2D storage, but 3D load operation -- according to table 8.15 of the OpenGL specification -- For a cube map, depth is the number of faces, for -- a cube map array, depth is the number of layer-faces Depth := GL.Types.Size'Max (1, Header.Array_Elements) * 6; when others => raise Program_Error; end case; T4 := Clock; -- TODO Handle KTXorientation key value pair -- Upload texture data declare Image_Size_Index : Stream_Element_Offset := Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value); Cube_Map : constant Boolean := Header.Kind = Texture_Cube_Map; begin for Level in 0 .. Levels - 1 loop declare Face_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index); -- If not Cube_Map, then Face_Size is the size of the whole level Cube_Padding : constant Natural := 3 - ((Face_Size + 3) mod 4); Image_Size : constant Natural := (if Cube_Map then (Face_Size + Cube_Padding) * 6 else Face_Size); -- If Cube_Map then Levels = 1 so no need to add it to the expression -- Compute size of the whole mipmap level Mip_Padding : constant Natural := 3 - ((Image_Size + 3) mod 4); Mipmap_Size : constant Natural := 4 + Image_Size + Mip_Padding; Offset : constant Stream_Element_Offset := Image_Size_Index + 4; pragma Assert (Offset + Stream_Element_Offset (Image_Size) - 1 <= Bytes.Value'Last); Image_Data : constant System.Address := Bytes (Offset)'Address; -- TODO Unpack_Alignment must be 4, but Load_From_Data wants 1 | 2 | 4 -- depending on Header.Data_Type Level_Width : constant GL.Types.Size := Texture.Width (Level); Level_Height : constant GL.Types.Size := Texture.Height (Level); Level_Depth : constant GL.Types.Size := Texture.Depth (Level); begin if Header.Compressed then Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data); else Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth, Header.Format, Header.Data_Type, Image_Data); end if; Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size); end; end loop; end; T5 := Clock; -- Generate a full mipmap pyramid if Mipmap_Levels = 0 if Header.Mipmap_Levels = 0 then Texture.Generate_Mipmap; end if; T6 := Clock; Messages.Log (Info, "Loaded texture " & Path & " in " & Logging.Trim (Logging.Image (T6 - T1))); Messages.Log (Info, " size: " & Logging.Trim (Width'Image) & " x " & Logging.Trim (Height'Image) & " x " & Logging.Trim (Depth'Image) & ", mipmap levels:" & Levels'Image); Messages.Log (Info, " kind: " & Header.Kind'Image); if Header.Compressed then Messages.Log (Info, " format: " & Header.Compressed_Format'Image); else Messages.Log (Info, " format: " & Header.Internal_Format'Image); end if; Messages.Log (Info, " statistics:"); Messages.Log (Info, " reading file: " & Logging.Image (T2 - T1)); Messages.Log (Info, " parsing header: " & Logging.Image (T3 - T2)); Messages.Log (Info, " storage: " & Logging.Image (T4 - T3)); Messages.Log (Info, " buffers: " & Logging.Image (T5 - T4)); if Header.Mipmap_Levels = 0 then Messages.Log (Info, " generating mipmap:" & Logging.Image (T6 - T5)); end if; return Texture; end; exception when Error : Orka.KTX.Invalid_Enum_Error => declare Message : constant String := Ada.Exceptions.Exception_Message (Error); begin raise Texture_Load_Error with Path & " has " & Message; end; end Read_Texture; function Read_Texture (Location : Locations.Location_Ptr; Path : String) return GL.Objects.Textures.Texture is Start_Time : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin return Read_Texture (Location.Read_Data (Path).Get, Path, Start_Time); end Read_Texture; overriding procedure Execute (Object : KTX_Load_Job; Context : Jobs.Execution_Context'Class) is Bytes : Byte_Array_Pointers.Constant_Reference := Object.Data.Bytes.Get; Path : String renames SU.To_String (Object.Data.Path); Resource : constant Texture_Ptr := new Texture'(others => <>); begin Resource.Texture.Replace_Element (Read_Texture (Bytes, Path, Object.Data.Start_Time)); -- Register resource at the resource manager Object.Manager.Add_Resource (Path, Resource_Ptr (Resource)); end Execute; ----------------------------------------------------------------------------- -- Loader -- ----------------------------------------------------------------------------- type KTX_Loader is limited new Loaders.Loader with record Manager : Managers.Manager_Ptr; end record; overriding function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx"); overriding procedure Load (Object : KTX_Loader; Data : Loaders.Resource_Data; Enqueue : not null access procedure (Element : Jobs.Job_Ptr); Location : Locations.Location_Ptr) is Job : constant Jobs.Job_Ptr := new KTX_Load_Job' (Jobs.Abstract_Job with Data => Data, Manager => Object.Manager); begin Enqueue (Job); end Load; function Create_Loader (Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr is (new KTX_Loader'(Manager => Manager)); ----------------------------------------------------------------------------- -- Writer -- ----------------------------------------------------------------------------- procedure Write_Texture (Texture : GL.Objects.Textures.Texture; Location : Locations.Writable_Location_Ptr; Path : String) is package Textures renames GL.Objects.Textures; package Pointers is new Textures.Texture_Pointers (Byte_Pointers); Format : GL.Pixels.Format := GL.Pixels.RGBA; Data_Type : GL.Pixels.Data_Type := GL.Pixels.Float; -- Note: unused if texture is compressed Base_Level : constant := 0; use Ada.Streams; use all type GL.Low_Level.Enums.Texture_Kind; use type GL.Types.Size; Compressed : constant Boolean := Texture.Compressed; Header : Orka.KTX.Header (Compressed); function Convert (Bytes : in out GL.Types.UByte_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); procedure Free is new Ada.Unchecked_Deallocation (Object => GL.Types.UByte_Array, Name => GL.Types.UByte_Array_Access); begin for Index in Bytes'Range loop declare Target_Index : constant Stream_Element_Offset := Stream_Element_Offset (Index - Bytes'First + 1); begin Result (Target_Index) := Stream_Element (Bytes (Index)); end; end loop; Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Convert (Bytes : in out Pointers.Element_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); begin Result.all := Bytes.all; Pointers.Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Get_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : Pointers.Element_Array_Access; begin Data := Pointers.Get_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Format, Data_Type); return Convert (Data); end Get_Data; function Get_Compressed_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : GL.Types.UByte_Array_Access; begin Data := Textures.Get_Compressed_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Texture.Compressed_Format); return Convert (Data); end Get_Compressed_Data; begin Header.Kind := Texture.Kind; Header.Width := Texture.Width (Base_Level); case Texture.Kind is when Texture_3D => Header.Height := Texture.Height (Base_Level); Header.Depth := Texture.Depth (Base_Level); when Texture_2D | Texture_2D_Array | Texture_Cube_Map | Texture_Cube_Map_Array => Header.Height := Texture.Height (Base_Level); Header.Depth := 0; when Texture_1D | Texture_1D_Array => Header.Height := 0; Header.Depth := 0; when others => raise Program_Error; end case; case Texture.Kind is when Texture_1D_Array => Header.Array_Elements := Texture.Height (Base_Level); when Texture_2D_Array => Header.Array_Elements := Texture.Depth (Base_Level); when Texture_Cube_Map_Array => Header.Array_Elements := Texture.Depth (Base_Level) / 6; when Texture_1D | Texture_2D | Texture_3D | Texture_Cube_Map => Header.Array_Elements := 0; when others => raise Program_Error; end case; Header.Mipmap_Levels := Texture.Mipmap_Levels; Header.Bytes_Key_Value := 0; if Compressed then Header.Compressed_Format := Texture.Compressed_Format; else declare Internal_Format : constant GL.Pixels.Internal_Format := Texture.Internal_Format; begin Format := GL.Pixels.Queries.Get_Texture_Format (Internal_Format, Texture.Kind); Data_Type := GL.Pixels.Queries.Get_Texture_Type (Internal_Format, Texture.Kind); Header.Internal_Format := Internal_Format; Header.Format := Format; Header.Data_Type := Data_Type; end; end if; declare function Get_Level_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is (if Compressed then Get_Compressed_Data (Level) else Get_Data (Level)); Bytes : constant Byte_Array_Pointers.Pointer := Orka.KTX.Create_KTX_Bytes (Header, Get_Level_Data'Access); begin Location.Write_Data (Path, Bytes.Get); end; end Write_Texture; end Orka.Resources.Textures.KTX;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System; with Ada.Exceptions; with Ada.Real_Time; with Ada.Unchecked_Deallocation; with GL.Low_Level.Enums; with GL.Types; with GL.Pixels.Extensions; with GL.Pixels.Queries; with Orka.Jobs; with Orka.Logging; with Orka.KTX; package body Orka.Resources.Textures.KTX is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; package Messages is new Orka.Logging.Messages (Resource_Loader); type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record Data : Loaders.Resource_Data; Manager : Managers.Manager_Ptr; end record; overriding procedure Execute (Object : KTX_Load_Job; Context : Jobs.Execution_Context'Class); ----------------------------------------------------------------------------- use all type Ada.Real_Time.Time; function Read_Texture (Bytes : Byte_Array_Pointers.Constant_Reference; Path : String; Start : Ada.Real_Time.Time) return GL.Objects.Textures.Texture is T1 : Ada.Real_Time.Time renames Start; T2 : constant Ada.Real_Time.Time := Clock; use Ada.Streams; use GL.Low_Level.Enums; use type GL.Types.Size; T3, T4, T5, T6 : Ada.Real_Time.Time; begin if not Orka.KTX.Valid_Identifier (Bytes) then raise Texture_Load_Error with Path & " is not a KTX file"; end if; declare Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes); Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels); Texture : GL.Objects.Textures.Texture (Header.Kind); Width : constant GL.Types.Size := Header.Width; Height : GL.Types.Size := Header.Height; Depth : GL.Types.Size := Header.Depth; begin T3 := Clock; if not Header.Compressed and then Header.Data_Type in GL.Pixels.Extensions.Packed_Data_Type then raise GL.Feature_Not_Supported_Exception with "Packed data type " & Header.Data_Type'Image & " is not supported yet"; end if; -- Allocate storage case Header.Kind is when Texture_2D_Array => Depth := Header.Array_Elements; when Texture_1D_Array => Height := Header.Array_Elements; pragma Assert (Depth = 0); when Texture_Cube_Map_Array => -- For a cube map array, depth is the number of layer-faces Depth := Header.Array_Elements * 6; when Texture_3D => null; when Texture_2D | Texture_Cube_Map => pragma Assert (Depth = 0); when Texture_1D => if Header.Compressed then raise Texture_Load_Error with Path & " has unknown 1D compressed format"; end if; pragma Assert (Height = 0); pragma Assert (Depth = 0); when others => raise Program_Error; end case; if Header.Compressed then Texture.Allocate_Storage (Levels, 1, Header.Compressed_Format, Width, Height, Depth); else Texture.Allocate_Storage (Levels, 1, Header.Internal_Format, Width, Height, Depth); end if; case Header.Kind is when Texture_1D => Height := 1; Depth := 1; when Texture_1D_Array | Texture_2D => Depth := 1; when Texture_2D_Array | Texture_3D => null; when Texture_Cube_Map | Texture_Cube_Map_Array => -- Texture_Cube_Map uses 2D storage, but 3D load operation -- according to table 8.15 of the OpenGL specification -- For a cube map, depth is the number of faces, for -- a cube map array, depth is the number of layer-faces Depth := GL.Types.Size'Max (1, Header.Array_Elements) * 6; when others => raise Program_Error; end case; T4 := Clock; -- TODO Handle KTXorientation key value pair -- Upload texture data declare Image_Size_Index : Stream_Element_Offset := Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value); Cube_Map : constant Boolean := Header.Kind = Texture_Cube_Map; begin for Level in 0 .. Levels - 1 loop declare Face_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index); -- If not Cube_Map, then Face_Size is the size of the whole level Cube_Padding : constant Natural := 3 - ((Face_Size + 3) mod 4); Image_Size : constant Natural := (if Cube_Map then (Face_Size + Cube_Padding) * 6 else Face_Size); -- If Cube_Map then Levels = 1 so no need to add it to the expression -- Compute size of the whole mipmap level Mip_Padding : constant Natural := 3 - ((Image_Size + 3) mod 4); Mipmap_Size : constant Natural := 4 + Image_Size + Mip_Padding; Offset : constant Stream_Element_Offset := Image_Size_Index + 4; pragma Assert (Offset + Stream_Element_Offset (Image_Size) - 1 <= Bytes.Value'Last); Image_Data : constant System.Address := Bytes (Offset)'Address; -- TODO Unpack_Alignment must be 4, but Load_From_Data wants 1 | 2 | 4 -- depending on Header.Data_Type Level_Width : constant GL.Types.Size := Texture.Width (Level); Level_Height : constant GL.Types.Size := Texture.Height (Level); Level_Depth : constant GL.Types.Size := Texture.Depth (Level); begin if Header.Compressed then Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data); else Texture.Load_From_Data (Level, 0, 0, 0, Level_Width, Level_Height, Level_Depth, Header.Format, Header.Data_Type, Image_Data); end if; Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size); end; end loop; end; T5 := Clock; -- Generate a full mipmap pyramid if Mipmap_Levels = 0 if Header.Mipmap_Levels = 0 then Texture.Generate_Mipmap; end if; T6 := Clock; Messages.Log (Info, "Loaded texture " & Path & " in " & Logging.Trim (Logging.Image (T6 - T1))); Messages.Log (Info, " size: " & Logging.Trim (Width'Image) & " x " & Logging.Trim (Height'Image) & " x " & Logging.Trim (Depth'Image) & ", mipmap levels:" & Levels'Image); Messages.Log (Info, " kind: " & Header.Kind'Image); if Header.Compressed then Messages.Log (Info, " format: " & Header.Compressed_Format'Image); else Messages.Log (Info, " format: " & Header.Internal_Format'Image); end if; Messages.Log (Info, " statistics:"); Messages.Log (Info, " reading file: " & Logging.Image (T2 - T1)); Messages.Log (Info, " parsing header: " & Logging.Image (T3 - T2)); Messages.Log (Info, " storage: " & Logging.Image (T4 - T3)); Messages.Log (Info, " buffers: " & Logging.Image (T5 - T4)); if Header.Mipmap_Levels = 0 then Messages.Log (Info, " generating mipmap:" & Logging.Image (T6 - T5)); end if; return Texture; end; exception when Error : Orka.KTX.Invalid_Enum_Error => declare Message : constant String := Ada.Exceptions.Exception_Message (Error); begin raise Texture_Load_Error with Path & " has " & Message; end; end Read_Texture; function Read_Texture (Location : Locations.Location_Ptr; Path : String) return GL.Objects.Textures.Texture is Start_Time : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin return Read_Texture (Location.Read_Data (Path).Get, Path, Start_Time); end Read_Texture; overriding procedure Execute (Object : KTX_Load_Job; Context : Jobs.Execution_Context'Class) is Bytes : Byte_Array_Pointers.Constant_Reference := Object.Data.Bytes.Get; Path : String renames SU.To_String (Object.Data.Path); Resource : constant Texture_Ptr := new Texture'(others => <>); begin Resource.Texture.Replace_Element (Read_Texture (Bytes, Path, Object.Data.Start_Time)); -- Register resource at the resource manager Object.Manager.Add_Resource (Path, Resource_Ptr (Resource)); end Execute; ----------------------------------------------------------------------------- -- Loader -- ----------------------------------------------------------------------------- type KTX_Loader is limited new Loaders.Loader with record Manager : Managers.Manager_Ptr; end record; overriding function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx"); overriding procedure Load (Object : KTX_Loader; Data : Loaders.Resource_Data; Enqueue : not null access procedure (Element : Jobs.Job_Ptr); Location : Locations.Location_Ptr) is Job : constant Jobs.Job_Ptr := new KTX_Load_Job' (Jobs.Abstract_Job with Data => Data, Manager => Object.Manager); begin Enqueue (Job); end Load; function Create_Loader (Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr is (new KTX_Loader'(Manager => Manager)); ----------------------------------------------------------------------------- -- Writer -- ----------------------------------------------------------------------------- procedure Write_Texture (Texture : GL.Objects.Textures.Texture; Location : Locations.Writable_Location_Ptr; Path : String) is package Textures renames GL.Objects.Textures; package Pointers is new Textures.Texture_Pointers (Byte_Pointers); Format : GL.Pixels.Format := GL.Pixels.RGBA; Data_Type : GL.Pixels.Data_Type := GL.Pixels.Float; -- Note: unused if texture is compressed Base_Level : constant := 0; use Ada.Streams; use all type GL.Low_Level.Enums.Texture_Kind; use type GL.Types.Size; Compressed : constant Boolean := Texture.Compressed; Header : Orka.KTX.Header (Compressed); function Convert (Bytes : in out GL.Types.UByte_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); procedure Free is new Ada.Unchecked_Deallocation (Object => GL.Types.UByte_Array, Name => GL.Types.UByte_Array_Access); begin for Index in Bytes'Range loop declare Target_Index : constant Stream_Element_Offset := Stream_Element_Offset (Index - Bytes'First + 1); begin Result (Target_Index) := Stream_Element (Bytes (Index)); end; end loop; Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Convert (Bytes : in out Pointers.Element_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); begin Result.all := Bytes.all; Pointers.Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Get_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : Pointers.Element_Array_Access; begin Data := Pointers.Get_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Format, Data_Type); return Convert (Data); end Get_Data; function Get_Compressed_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : GL.Types.UByte_Array_Access; begin Data := Textures.Get_Compressed_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Texture.Compressed_Format); return Convert (Data); end Get_Compressed_Data; begin Header.Kind := Texture.Kind; Header.Width := Texture.Width (Base_Level); case Texture.Kind is when Texture_3D => Header.Height := Texture.Height (Base_Level); Header.Depth := Texture.Depth (Base_Level); when Texture_2D | Texture_2D_Array | Texture_Cube_Map | Texture_Cube_Map_Array => Header.Height := Texture.Height (Base_Level); Header.Depth := 0; when Texture_1D | Texture_1D_Array => Header.Height := 0; Header.Depth := 0; when others => raise Program_Error; end case; case Texture.Kind is when Texture_1D_Array => Header.Array_Elements := Texture.Height (Base_Level); when Texture_2D_Array => Header.Array_Elements := Texture.Depth (Base_Level); when Texture_Cube_Map_Array => Header.Array_Elements := Texture.Depth (Base_Level) / 6; when Texture_1D | Texture_2D | Texture_3D | Texture_Cube_Map => Header.Array_Elements := 0; when others => raise Program_Error; end case; Header.Mipmap_Levels := Texture.Mipmap_Levels; Header.Bytes_Key_Value := 0; if Compressed then Header.Compressed_Format := Texture.Compressed_Format; else declare Internal_Format : constant GL.Pixels.Internal_Format := Texture.Internal_Format; begin Format := GL.Pixels.Queries.Get_Texture_Format (Internal_Format, Texture.Kind); Data_Type := GL.Pixels.Queries.Get_Texture_Type (Internal_Format, Texture.Kind); Header.Internal_Format := Internal_Format; Header.Format := Format; Header.Data_Type := Data_Type; end; end if; declare function Get_Level_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is (if Compressed then Get_Compressed_Data (Level) else Get_Data (Level)); Bytes : constant Byte_Array_Pointers.Pointer := Orka.KTX.Create_KTX_Bytes (Header, Get_Level_Data'Access); begin Location.Write_Data (Path, Bytes.Get); end; end Write_Texture; end Orka.Resources.Textures.KTX;
Raise exception if KTX file uses an uncompressed packed data type
orka: Raise exception if KTX file uses an uncompressed packed data type Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
22214040735a8bf332908cb5eb09bead1ae4561b
src/el-functions-default.adb
src/el-functions-default.adb
----------------------------------------------------------------------- -- EL.Functions -- Default function mapper -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The default function mapper allows to register -- The expression context provides information to resolve runtime -- information when evaluating an expression. The context provides -- a resolver whose role is to find variables given their name. package body EL.Functions.Default is -- ------------------------------ -- Default Function mapper -- ------------------------------ -- use Function_Maps; -- ------------------------------ -- Find the function knowing its name. -- ------------------------------ function Get_Function (Mapper : Default_Function_Mapper; Namespace : String; Name : String) return Function_Access is Full_Name : constant String := Namespace & ":" & Name; C : constant Cursor := Mapper.Map.Find (Key => To_Unbounded_String (Full_Name)); begin if Has_Element (C) then return Element (C); end if; raise No_Function; end Get_Function; -- ------------------------------ -- Bind a name to a function. -- ------------------------------ procedure Set_Function (Mapper : in out Default_Function_Mapper; Namespace : in String; Name : in String; Func : in Function_Access) is Full_Name : constant String := Namespace & ":" & Name; begin Mapper.Map.Include (Key => To_Unbounded_String (Full_Name), New_Item => Func); end Set_Function; -- ------------------------------ -- Truncate the string representation represented by <b>Value</b> to -- the length specified by <b>Size</b>. -- ------------------------------ function Truncate (Value : EL.Objects.Object; Size : EL.Objects.Object) return EL.Objects.Object is Cnt : constant Integer := To_Integer (Size); begin if Cnt <= 0 then return To_Object (String '("")); end if; if Get_Type (Value) = TYPE_WIDE_STRING then declare S : constant Wide_Wide_String := To_Wide_Wide_String (Value); begin return To_Object (S (1 .. Cnt)); end; else -- Optimized case: use a String if we can. declare S : constant String := To_String (Value); begin return To_Object (S (1 .. Cnt)); end; end if; end Truncate; end EL.Functions.Default;
----------------------------------------------------------------------- -- EL.Functions -- Default function mapper -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The default function mapper allows to register -- The expression context provides information to resolve runtime -- information when evaluating an expression. The context provides -- a resolver whose role is to find variables given their name. package body EL.Functions.Default is -- ------------------------------ -- Default Function mapper -- ------------------------------ -- use Function_Maps; -- ------------------------------ -- Find the function knowing its name. -- ------------------------------ function Get_Function (Mapper : Default_Function_Mapper; Namespace : String; Name : String) return Function_Access is Full_Name : constant String := Namespace & ":" & Name; C : constant Cursor := Mapper.Map.Find (Key => To_Unbounded_String (Full_Name)); begin if Has_Element (C) then return Element (C); end if; raise No_Function with "Function '" & Full_Name & "' not found"; end Get_Function; -- ------------------------------ -- Bind a name to a function. -- ------------------------------ procedure Set_Function (Mapper : in out Default_Function_Mapper; Namespace : in String; Name : in String; Func : in Function_Access) is Full_Name : constant String := Namespace & ":" & Name; begin Mapper.Map.Include (Key => To_Unbounded_String (Full_Name), New_Item => Func); end Set_Function; -- ------------------------------ -- Truncate the string representation represented by <b>Value</b> to -- the length specified by <b>Size</b>. -- ------------------------------ function Truncate (Value : EL.Objects.Object; Size : EL.Objects.Object) return EL.Objects.Object is Cnt : constant Integer := To_Integer (Size); begin if Cnt <= 0 then return To_Object (String '("")); end if; if Get_Type (Value) = TYPE_WIDE_STRING then declare S : constant Wide_Wide_String := To_Wide_Wide_String (Value); begin return To_Object (S (1 .. Cnt)); end; else -- Optimized case: use a String if we can. declare S : constant String := To_String (Value); begin return To_Object (S (1 .. Cnt)); end; end if; end Truncate; end EL.Functions.Default;
Add a message in the Not_Found exception
Add a message in the Not_Found exception
Ada
apache-2.0
stcarrez/ada-el
9496af418a57a78692fc1585c2cf4c2e2ca201a3
resources/scripts/api/gitlab.ads
resources/scripts/api/gitlab.ads
-- Copyright 2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. name = "GitLab" type = "api" function start() set_rate_limit(1) end function check() local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c ~= nil and c.key ~= nil and c.key ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local scopes = {"issues", "blobs", "notes"} for _, s in pairs(scopes) do scrape(ctx, { url=build_url(domain, s), headers={['PRIVATE-TOKEN']=c.key}, }) end end function build_url(domain, scope) return "https://gitlab.com/api/v4/search?scope=" .. scope .. "&search=" .. domain end
-- Copyright 2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. name = "GitLab" type = "api" function start() set_rate_limit(1) end function check() local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c ~= nil and c.key ~= nil and c.key ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local scopes = {"issues", "blobs", "notes"} for _, s in pairs(scopes) do scrape(ctx, { url=build_url(domain, s), headers={['PRIVATE-TOKEN']=c.key}, }) end end function build_url(domain, scope) return "https://gitlab.com/api/v4/search?scope=" .. scope .. "&search=" .. domain:gsub("%.", "[.]") end
Fix Gitlab data source script
Fix Gitlab data source script
Ada
apache-2.0
caffix/amass,caffix/amass
c43406d481641376d12bc4dd9172090e40faac9a
src/orka/implementation/orka-transforms-simd_quaternions.adb
src/orka/implementation/orka-transforms-simd_quaternions.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Quaternions is package EF is new Ada.Numerics.Generic_Elementary_Functions (Vectors.Element_Type); function Vector_Part (Elements : Quaternion) return Vector4 is begin return Result : Vector4 := Vector4 (Elements) do Result (W) := 0.0; end return; end Vector_Part; function "*" (Left, Right : Quaternion) return Quaternion is use Vectors; Lv : constant Vector4 := Vector_Part (Left); Rv : constant Vector4 := Vector_Part (Right); Ls : constant Vectors.Element_Type := Left (W); Rs : constant Vectors.Element_Type := Right (W); V : constant Vector4 := Ls * Rv + Rs * Lv + Vectors.Cross (Lv, Rv); S : constant Element_Type := Ls * Rs - Vectors.Dot (Lv, Rv); begin return Result : Quaternion := Quaternion (V) do Result (W) := S; end return; end "*"; function Conjugate (Elements : Quaternion) return Quaternion is Element_W : constant Vectors.Element_Type := Elements (W); use Vectors; begin return Result : Quaternion := Quaternion (-Vector4 (Elements)) do Result (W) := Element_W; end return; end Conjugate; function Norm (Elements : Quaternion) return Vectors.Element_Type is (Vectors.Magnitude (Vector4 (Elements))); function Normalize (Elements : Quaternion) return Quaternion is (Quaternion (Vectors.Normalize (Vector4 (Elements)))); function Normalized (Elements : Quaternion) return Boolean is (Vectors.Normalized (Vector4 (Elements))); function To_Axis_Angle (Elements : Quaternion) return Axis_Angle is use type Vectors.Element_Type; Angle : constant Vectors.Element_Type := EF.Arccos (Elements (W)) * 2.0; SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0); use Vectors; Axis : Vector4 := Vector4 (Elements) * (1.0 / SA); begin Axis (W) := 0.0; return (Axis => Axis, Angle => Angle); end To_Axis_Angle; function R (Axis : Vector4; Angle : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; CA : constant Vectors.Element_Type := EF.Cos (Angle / 2.0); SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0); use Vectors; begin return Result : Quaternion := Quaternion (Axis * SA) do Result (W) := CA; end return; end R; function R (Left, Right : Vector4) return Quaternion is use type Vectors.Element_Type; S : constant Vector4 := Vectors.Normalize (Left); T : constant Vector4 := Vectors.Normalize (Right); E : constant Vectors.Element_Type := Vectors.Dot (S, T); SRE : constant Vectors.Element_Type := EF.Sqrt (2.0 * (1.0 + E)); use Vectors; begin -- Division by zero if Left and Right are in opposite direction. -- Use rotation axis perpendicular to s and angle of 180 degrees if SRE /= 0.0 then -- Equation 4.53 from chapter 4.3 Quaternions from Real-Time Rendering -- (third edition, 2008) declare Result : Quaternion := Quaternion ((1.0 / SRE) * Vectors.Cross (S, T)); begin Result (W) := SRE / 2.0; return Normalize (Result); end; else if abs S (Z) < abs S (X) then return R ((S (Y), -S (X), 0.0, 0.0), Ada.Numerics.Pi); else return R ((0.0, -S (Z), S (Y), 0.0), Ada.Numerics.Pi); end if; end if; end R; function Difference (Left, Right : Quaternion) return Quaternion is begin return Right * Conjugate (Left); end Difference; procedure Rotate_At_Origin (Vector : in out Vector4; Elements : Quaternion) is Result : Vectors.Vector_Type; begin Result := Vectors.Vector_Type (Elements * Quaternion (Vector) * Conjugate (Elements)); Vector := Result; end Rotate_At_Origin; function Lerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; use Vectors; begin return Normalize (Quaternion ((1.0 - Time) * Vector4 (Left) + Time * Vector4 (Right))); end Lerp; function Slerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; Cos_Angle : constant Vectors.Element_Type := Vectors.Dot (Vector4 (Left), Vector4 (Right)); Angle : constant Vectors.Element_Type := EF.Arccos (Cos_Angle); SA : constant Vectors.Element_Type := EF.Sin (Angle); SL : constant Vectors.Element_Type := EF.Sin ((1.0 - Time) * Angle); SR : constant Vectors.Element_Type := EF.Sin (Time * Angle); use Vectors; begin return Quaternion ((SL / SA) * Vector4 (Left) + (SR / SA) * Vector4 (Right)); end Slerp; function Image (Elements : Quaternion) return String is (Vectors.Image (Vectors.Vector_Type (Elements))); end Orka.Transforms.SIMD_Quaternions;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; package body Orka.Transforms.SIMD_Quaternions is package EF is new Ada.Numerics.Generic_Elementary_Functions (Vectors.Element_Type); function Vector_Part (Elements : Quaternion) return Vector4 is begin return Result : Vector4 := Vector4 (Elements) do Result (W) := 0.0; end return; end Vector_Part; function "*" (Left, Right : Quaternion) return Quaternion is use Vectors; Lv : constant Vector4 := Vector_Part (Left); Rv : constant Vector4 := Vector_Part (Right); Ls : constant Vectors.Element_Type := Left (W); Rs : constant Vectors.Element_Type := Right (W); V : constant Vector4 := Ls * Rv + Rs * Lv + Vectors.Cross (Lv, Rv); S : constant Element_Type := Ls * Rs - Vectors.Dot (Lv, Rv); begin return Result : Quaternion := Quaternion (V) do Result (W) := S; end return; end "*"; function Conjugate (Elements : Quaternion) return Quaternion is Element_W : constant Vectors.Element_Type := Elements (W); use Vectors; begin return Result : Quaternion := Quaternion (-Vector4 (Elements)) do Result (W) := Element_W; end return; end Conjugate; function Norm (Elements : Quaternion) return Vectors.Element_Type is (Vectors.Magnitude (Vector4 (Elements))); function Normalize (Elements : Quaternion) return Quaternion is (Quaternion (Vectors.Normalize (Vector4 (Elements)))); function Normalized (Elements : Quaternion) return Boolean is (Vectors.Normalized (Vector4 (Elements))); function To_Axis_Angle (Elements : Quaternion) return Axis_Angle is use type Vectors.Element_Type; Angle : constant Vectors.Element_Type := EF.Arccos (Elements (W)) * 2.0; SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0); begin if SA /= 0.0 then declare use Vectors; Axis : Vector4 := Vector4 (Elements) * (1.0 / SA); begin Axis (W) := 0.0; return (Axis => Axis, Angle => Angle); end; else -- Singularity occurs when angle is 0. Return an arbitrary axis return (Axis => (1.0, 0.0, 0.0, 0.0), Angle => 0.0); end if; end To_Axis_Angle; function R (Axis : Vector4; Angle : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; CA : constant Vectors.Element_Type := EF.Cos (Angle / 2.0); SA : constant Vectors.Element_Type := EF.Sin (Angle / 2.0); use Vectors; begin return Result : Quaternion := Quaternion (Axis * SA) do Result (W) := CA; end return; end R; function R (Left, Right : Vector4) return Quaternion is use type Vectors.Element_Type; S : constant Vector4 := Vectors.Normalize (Left); T : constant Vector4 := Vectors.Normalize (Right); E : constant Vectors.Element_Type := Vectors.Dot (S, T); SRE : constant Vectors.Element_Type := EF.Sqrt (2.0 * (1.0 + E)); use Vectors; begin -- Division by zero if Left and Right are in opposite direction. -- Use rotation axis perpendicular to s and angle of 180 degrees if SRE /= 0.0 then -- Equation 4.53 from chapter 4.3 Quaternions from Real-Time Rendering -- (third edition, 2008) declare Result : Quaternion := Quaternion ((1.0 / SRE) * Vectors.Cross (S, T)); begin Result (W) := SRE / 2.0; return Normalize (Result); end; else if abs S (Z) < abs S (X) then return R ((S (Y), -S (X), 0.0, 0.0), Ada.Numerics.Pi); else return R ((0.0, -S (Z), S (Y), 0.0), Ada.Numerics.Pi); end if; end if; end R; function Difference (Left, Right : Quaternion) return Quaternion is begin return Right * Conjugate (Left); end Difference; procedure Rotate_At_Origin (Vector : in out Vector4; Elements : Quaternion) is Result : Vectors.Vector_Type; begin Result := Vectors.Vector_Type (Elements * Quaternion (Vector) * Conjugate (Elements)); Vector := Result; end Rotate_At_Origin; function Lerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; use Vectors; begin return Normalize (Quaternion ((1.0 - Time) * Vector4 (Left) + Time * Vector4 (Right))); end Lerp; function Slerp (Left, Right : Quaternion; Time : Vectors.Element_Type) return Quaternion is use type Vectors.Element_Type; Cos_Angle : constant Vectors.Element_Type := Vectors.Dot (Vector4 (Left), Vector4 (Right)); Angle : constant Vectors.Element_Type := EF.Arccos (Cos_Angle); SA : constant Vectors.Element_Type := EF.Sin (Angle); SL : constant Vectors.Element_Type := EF.Sin ((1.0 - Time) * Angle); SR : constant Vectors.Element_Type := EF.Sin (Time * Angle); use Vectors; begin return Quaternion ((SL / SA) * Vector4 (Left) + (SR / SA) * Vector4 (Right)); end Slerp; function Image (Elements : Quaternion) return String is (Vectors.Image (Vectors.Vector_Type (Elements))); end Orka.Transforms.SIMD_Quaternions;
Fix function To_Axis_Angle to handle singularity at 0 deg rotation
orka: Fix function To_Axis_Angle to handle singularity at 0 deg rotation Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
e98d68e6c7687974cef37632ce4139faa4e0f5a5
src/util-encoders-base64.adb
src/util-encoders-base64.adb
----------------------------------------------------------------------- -- util-encoders-base64 -- Encode/Decode a stream in base64adecimal -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams; package body Util.Encoders.Base64 is use Interfaces; use Ada; use type Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Encode the 64-bit value to LEB128 and then base64url. -- ------------------------------ function Encode (Value : in Interfaces.Unsigned_64) return String is E : Encoder; Data : Ada.Streams.Stream_Element_Array (1 .. 10); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Result : String (1 .. 16); Buf : Ada.Streams.Stream_Element_Array (1 .. Result'Length); for Buf'Address use Result'Address; pragma Import (Ada, Buf); begin -- Encode the integer to LEB128 in the data buffer. Encode_LEB128 (Into => Data, Pos => Data'First, Val => Value, Last => Last); -- Encode the data buffer in base64url. E.Set_URL_Mode (True); E.Transform (Data => Data (Data'First .. Last), Into => Buf, Last => Last, Encoded => Encoded); -- Strip the '=' or '==' at end of base64url. if Result (Positive (Last)) /= '=' then return Result (Result'First .. Positive (Last)); elsif Result (Positive (Last) - 1) /= '=' then return Result (Result'First .. Positive (Last) - 1); else return Result (Result'First .. Positive (Last) - 2); end if; end Encode; -- ------------------------------ -- Decode the base64url string and then the LEB128 integer. -- Raise the Encoding_Error if the string is invalid and cannot be decoded. -- ------------------------------ function Decode (Value : in String) return Interfaces.Unsigned_64 is D : Decoder; Buf : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2); R : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Result : Interfaces.Unsigned_64; End_Pos : constant Ada.Streams.Stream_Element_Offset := Value'Length + ((4 - (Value'Length mod 4)) mod 4); begin Util.Streams.Copy (Into => Buf (1 .. Value'Length), From => Value); -- Set back the '=' for the base64url (pad to multiple of 4. Buf (Value'Length + 1) := Character'Pos ('='); Buf (Value'Length + 2) := Character'Pos ('='); -- Decode using base64url D.Set_URL_Mode (True); D.Transform (Data => Buf (Buf'First .. End_Pos), Into => R, Last => Last, Encoded => Encoded); if Encoded /= End_Pos then raise Encoding_Error with "Input string is too short"; end if; -- Decode the LEB128 number. Decode_LEB128 (From => R (R'First .. Last), Pos => R'First, Val => Result, Last => Encoded); -- Check that everything was decoded. if Last + 1 /= Encoded then raise Encoding_Error with "Input string contains garbage at the end"; end if; return Result; end Decode; -- ------------------------------ -- Encodes the binary input stream represented by <b>Data</b> into -- the a base64 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) is Pos : Ada.Streams.Stream_Element_Offset := Into'First; I : Ada.Streams.Stream_Element_Offset := Data'First; C1, C2 : Unsigned_8; Alphabet : constant Alphabet_Access := E.Alphabet; begin while I <= Data'Last loop if Pos + 4 > Into'Last + 1 then Last := Pos - 1; Encoded := I - 1; return; end if; -- Encode the first byte, add padding if necessary. C1 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Right (C1, 2)); if I = Data'Last then Into (Pos + 1) := Alphabet (Shift_Left (C1 and 3, 4)); Into (Pos + 2) := Character'Pos ('='); Into (Pos + 3) := Character'Pos ('='); Last := Pos + 3; Encoded := Data'Last; return; end if; -- Encode the second byte, add padding if necessary. C2 := Unsigned_8 (Data (I + 1)); Into (Pos + 1) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4)); if I = Data'Last - 1 then Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2)); Into (Pos + 3) := Character'Pos ('='); Last := Pos + 3; Encoded := Data'Last; return; end if; -- Encode the third byte C1 := Unsigned_8 (Data (I + 2)); Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6)); Into (Pos + 3) := Alphabet (C1 and 16#03F#); Pos := Pos + 4; I := I + 3; end loop; Last := Pos - 1; Encoded := Data'Last; end Transform; -- ------------------------------ -- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ procedure Set_URL_Mode (E : in out Encoder; Mode : in Boolean) is begin if Mode then E.Alphabet := BASE64_URL_ALPHABET'Access; else E.Alphabet := BASE64_ALPHABET'Access; end if; end Set_URL_Mode; -- ------------------------------ -- Create a base64 encoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ function Create_URL_Encoder return Transformer_Access is begin return new Encoder '(Alphabet => BASE64_URL_ALPHABET'Access); end Create_URL_Encoder; -- ------------------------------ -- Decodes the base64 input stream represented by <b>Data</b> into -- the binary 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) is use Ada.Streams; Pos : Ada.Streams.Stream_Element_Offset := Into'First; I : Ada.Streams.Stream_Element_Offset := Data'First; C1, C2 : Ada.Streams.Stream_Element; Val1, Val2 : Unsigned_8; Values : constant Alphabet_Values_Access := E.Values; begin while I <= Data'Last loop if Pos + 3 > Into'Last + 1 then Last := Pos - 1; Encoded := I - 1; return; end if; -- Decode the first two bytes to produce the first output byte C1 := Data (I); Val1 := Values (C1); if (Val1 and 16#C0#) /= 0 then raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'"; end if; C2 := Data (I + 1); Val2 := Values (C2); if (Val2 and 16#C0#) /= 0 then raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'"; end if; Into (Pos) := Stream_Element (Shift_Left (Val1, 2) or Shift_Right (Val2, 4)); if I + 2 > Data'Last then Encoded := I + 1; Last := Pos; return; end if; -- Decode the next byte C1 := Data (I + 2); Val1 := Values (C1); if (Val1 and 16#C0#) /= 0 then if C1 /= Character'Pos ('=') then raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'"; end if; Encoded := I + 3; Last := Pos; return; end if; Into (Pos + 1) := Stream_Element (Shift_Left (Val2, 4) or Shift_Right (Val1, 2)); if I + 3 > Data'Last then Encoded := I + 2; Last := Pos + 1; return; end if; C2 := Data (I + 3); Val2 := Values (C2); if (Val2 and 16#C0#) /= 0 then if C2 /= Character'Pos ('=') then raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'"; end if; Encoded := I + 3; Last := Pos + 1; return; end if; Into (Pos + 2) := Stream_Element (Shift_Left (Val1, 6) or Val2); Pos := Pos + 3; I := I + 4; end loop; Last := Pos - 1; Encoded := Data'Last; end Transform; -- ------------------------------ -- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ procedure Set_URL_Mode (E : in out Decoder; Mode : in Boolean) is begin if Mode then E.Values := BASE64_URL_VALUES'Access; else E.Values := BASE64_VALUES'Access; end if; end Set_URL_Mode; -- ------------------------------ -- Create a base64 decoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ function Create_URL_Decoder return Transformer_Access is begin return new Decoder '(Values => BASE64_URL_VALUES'Access); end Create_URL_Decoder; end Util.Encoders.Base64;
----------------------------------------------------------------------- -- util-encoders-base64 -- Encode/Decode a stream in base64adecimal -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Streams; package body Util.Encoders.Base64 is use Interfaces; use Ada; use type Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Encode the 64-bit value to LEB128 and then base64url. -- ------------------------------ function Encode (Value : in Interfaces.Unsigned_64) return String is E : Encoder; Data : Ada.Streams.Stream_Element_Array (1 .. 10); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Result : String (1 .. 16); Buf : Ada.Streams.Stream_Element_Array (1 .. Result'Length); for Buf'Address use Result'Address; pragma Import (Ada, Buf); begin -- Encode the integer to LEB128 in the data buffer. Encode_LEB128 (Into => Data, Pos => Data'First, Val => Value, Last => Last); -- Encode the data buffer in base64url. E.Set_URL_Mode (True); E.Transform (Data => Data (Data'First .. Last), Into => Buf, Last => Last, Encoded => Encoded); E.Finish (Into => Buf (Last + 1 .. Buf'Last), Last => Last); -- Strip the '=' or '==' at end of base64url. if Result (Positive (Last)) /= '=' then return Result (Result'First .. Positive (Last)); elsif Result (Positive (Last) - 1) /= '=' then return Result (Result'First .. Positive (Last) - 1); else return Result (Result'First .. Positive (Last) - 2); end if; end Encode; -- ------------------------------ -- Decode the base64url string and then the LEB128 integer. -- Raise the Encoding_Error if the string is invalid and cannot be decoded. -- ------------------------------ function Decode (Value : in String) return Interfaces.Unsigned_64 is D : Decoder; Buf : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2); R : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Result : Interfaces.Unsigned_64; End_Pos : constant Ada.Streams.Stream_Element_Offset := Value'Length + ((4 - (Value'Length mod 4)) mod 4); begin if Buf'Length < End_Pos then raise Encoding_Error with "Input string is too short"; end if; Util.Streams.Copy (Into => Buf (1 .. Value'Length), From => Value); -- Set back the '=' for the base64url (pad to multiple of 4. Buf (Value'Length + 1) := Character'Pos ('='); Buf (Value'Length + 2) := Character'Pos ('='); -- Decode using base64url D.Set_URL_Mode (True); D.Transform (Data => Buf (Buf'First .. End_Pos), Into => R, Last => Last, Encoded => Encoded); if Encoded /= End_Pos then raise Encoding_Error with "Input string is too short"; end if; -- Decode the LEB128 number. Decode_LEB128 (From => R (R'First .. Last), Pos => R'First, Val => Result, Last => Encoded); -- Check that everything was decoded. if Last + 1 /= Encoded then raise Encoding_Error with "Input string contains garbage at the end"; end if; return Result; end Decode; -- ------------------------------ -- Encodes the binary input stream represented by <b>Data</b> into -- the a base64 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) is Pos : Ada.Streams.Stream_Element_Offset := Into'First; I : Ada.Streams.Stream_Element_Offset := Data'First; C1, C2 : Unsigned_8; Alphabet : constant Alphabet_Access := E.Alphabet; begin while E.Count /= 0 and I <= Data'Last loop if E.Count = 2 then C1 := E.Value; C2 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4)); Pos := Pos + 1; I := I + 1; E.Count := 1; E.Value := C2; else C2 := E.Value; C1 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6)); Into (Pos + 1) := Alphabet (C1 and 16#03F#); Pos := Pos + 2; I := I + 1; E.Count := 0; end if; end loop; while I <= Data'Last loop if Pos + 4 > Into'Last + 1 then Last := Pos - 1; Encoded := I - 1; E.Count := 0; return; end if; -- Encode the first byte, add padding if necessary. C1 := Unsigned_8 (Data (I)); Into (Pos) := Alphabet (Shift_Right (C1, 2)); if I = Data'Last then E.Value := C1; E.Count := 2; Last := Pos; Encoded := Data'Last; return; end if; -- Encode the second byte, add padding if necessary. C2 := Unsigned_8 (Data (I + 1)); Into (Pos + 1) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4)); if I = Data'Last - 1 then E.Value := C2; E.Count := 1; Last := Pos + 1; Encoded := Data'Last; return; end if; -- Encode the third byte C1 := Unsigned_8 (Data (I + 2)); Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6)); Into (Pos + 3) := Alphabet (C1 and 16#03F#); Pos := Pos + 4; I := I + 3; end loop; E.Count := 0; Last := Pos - 1; Encoded := Data'Last; end Transform; -- ------------------------------ -- 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) is Pos : constant Ada.Streams.Stream_Element_Offset := Into'First; begin if E.Count = 2 then Into (Pos) := E.Alphabet (Shift_Left (E.Value and 3, 4)); Into (Pos + 1) := Character'Pos ('='); Into (Pos + 2) := Character'Pos ('='); Last := Pos + 2; E.Count := 0; elsif E.Count = 1 then Into (Pos) := E.Alphabet (Shift_Left (E.Value and 16#0F#, 2)); Into (Pos + 1) := Character'Pos ('='); Last := Pos + 1; E.Count := 0; else Last := Pos - 1; end if; end Finish; -- ------------------------------ -- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ procedure Set_URL_Mode (E : in out Encoder; Mode : in Boolean) is begin if Mode then E.Alphabet := BASE64_URL_ALPHABET'Access; else E.Alphabet := BASE64_ALPHABET'Access; end if; end Set_URL_Mode; -- ------------------------------ -- Create a base64 encoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ function Create_URL_Encoder return Transformer_Access is begin return new Encoder '(Alphabet => BASE64_URL_ALPHABET'Access, others => <>); end Create_URL_Encoder; -- ------------------------------ -- Decodes the base64 input stream represented by <b>Data</b> into -- the binary 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) is use Ada.Streams; Pos : Ada.Streams.Stream_Element_Offset := Into'First; I : Ada.Streams.Stream_Element_Offset := Data'First; C1, C2 : Ada.Streams.Stream_Element; Val1, Val2 : Unsigned_8; Values : constant Alphabet_Values_Access := E.Values; begin while I <= Data'Last loop if Pos + 3 > Into'Last + 1 then Last := Pos - 1; Encoded := I - 1; return; end if; -- Decode the first two bytes to produce the first output byte C1 := Data (I); Val1 := Values (C1); if (Val1 and 16#C0#) /= 0 then raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'"; end if; C2 := Data (I + 1); Val2 := Values (C2); if (Val2 and 16#C0#) /= 0 then raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'"; end if; Into (Pos) := Stream_Element (Shift_Left (Val1, 2) or Shift_Right (Val2, 4)); if I + 2 > Data'Last then Encoded := I + 1; Last := Pos; return; end if; -- Decode the next byte C1 := Data (I + 2); Val1 := Values (C1); if (Val1 and 16#C0#) /= 0 then if C1 /= Character'Pos ('=') then raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'"; end if; Encoded := I + 3; Last := Pos; return; end if; Into (Pos + 1) := Stream_Element (Shift_Left (Val2, 4) or Shift_Right (Val1, 2)); if I + 3 > Data'Last then Encoded := I + 2; Last := Pos + 1; return; end if; C2 := Data (I + 3); Val2 := Values (C2); if (Val2 and 16#C0#) /= 0 then if C2 /= Character'Pos ('=') then raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'"; end if; Encoded := I + 3; Last := Pos + 1; return; end if; Into (Pos + 2) := Stream_Element (Shift_Left (Val1, 6) or Val2); Pos := Pos + 3; I := I + 4; end loop; Last := Pos - 1; Encoded := Data'Last; end Transform; -- ------------------------------ -- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ procedure Set_URL_Mode (E : in out Decoder; Mode : in Boolean) is begin if Mode then E.Values := BASE64_URL_VALUES'Access; else E.Values := BASE64_VALUES'Access; end if; end Set_URL_Mode; -- ------------------------------ -- Create a base64 decoder using the URL alphabet. -- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters. -- ------------------------------ function Create_URL_Decoder return Transformer_Access is begin return new Decoder '(Values => BASE64_URL_VALUES'Access); end Create_URL_Decoder; end Util.Encoders.Base64;
Implement the Finish operation to handle the end of a Base64 conversion
Implement the Finish operation to handle the end of a Base64 conversion
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
48a1aff4e208a563e68a2566fbd368761b30e8f2
src/util-serialize-tools.adb
src/util-serialize-tools.adb
----------------------------------------------------------------------- -- util-serialize-tools -- Tools to Serialize objects in various formats -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.Mappers.Record_Mapper; package body Util.Serialize.Tools is type Object_Field is (FIELD_NAME, FIELD_VALUE); type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class; type Object_Mapper_Context is record Map : Object_Map_Access; Name : Util.Beans.Objects.Object; end record; type Object_Mapper_Context_Access is access all Object_Mapper_Context; procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_VALUE => Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value); Into.Name := Util.Beans.Objects.Null_Object; end case; end Set_Member; package Object_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context, Element_Type_Access => Object_Mapper_Context_Access, Fields => Object_Field, Set_Member => Set_Member); JSON_Mapping : aliased Object_Mapper.Mapper; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b> -- JSON stream. Use the <b>Name</b> as the name of the JSON object. -- ----------------------- procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream; Name : in String; Map : in Util.Beans.Objects.Maps.Map) is use type Ada.Containers.Count_Type; procedure Write (Name : in String; Value : in Util.Beans.Objects.Object); procedure Write (Name : in String; Value : in Util.Beans.Objects.Object) is begin Output.Start_Entity (Name => ""); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_Attribute (Name => "value", Value => Value); Output.End_Entity (Name => ""); end Write; begin if Map.Length > 0 then declare Iter : Util.Beans.Objects.Maps.Cursor := Map.First; begin Output.Start_Array (Name => Name); while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access); Util.Beans.Objects.Maps.Next (Iter); end loop; Output.End_Array (Name => Name); end; end if; end To_JSON; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into an XML stream. -- Returns the JSON string that contains a serialization of the object maps. -- ----------------------- function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is use type Ada.Containers.Count_Type; begin if Map.Length = 0 then return ""; end if; declare Output : Util.Serialize.IO.JSON.Output_Stream; begin Output.Initialize (Size => 10000); Output.Start_Document; To_JSON (Output, "params", Map); Output.End_Document; return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Output)); end; end To_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. The object map passed in <b>Map</b> can contain existing values. -- They will be overriden by the JSON values. -- ----------------------- procedure From_JSON (Content : in String; Map : in out Util.Beans.Objects.Maps.Map) is Parser : Util.Serialize.IO.JSON.Parser; Context : aliased Object_Mapper_Context; begin if Content'Length > 0 then Context.Map := Map'Unchecked_Access; Parser.Add_Mapping ("/params", JSON_Mapping'Access); Object_Mapper.Set_Context (Parser, Context'Unchecked_Access); Parser.Parse_String (Content); end if; end From_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. -- Returns the object map that was restored. -- ----------------------- function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is Result : Util.Beans.Objects.Maps.Map; begin From_JSON (Content, Result); return Result; end From_JSON; begin JSON_Mapping.Add_Mapping ("name", FIELD_NAME); JSON_Mapping.Add_Mapping ("value", FIELD_VALUE); end Util.Serialize.Tools;
----------------------------------------------------------------------- -- util-serialize-tools -- Tools to Serialize objects in various formats -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.Mappers.Record_Mapper; package body Util.Serialize.Tools is type Object_Field is (FIELD_NAME, FIELD_VALUE); type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class; type Object_Mapper_Context is record Map : Object_Map_Access; Name : Util.Beans.Objects.Object; end record; type Object_Mapper_Context_Access is access all Object_Mapper_Context; procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object); procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_VALUE => Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value); Into.Name := Util.Beans.Objects.Null_Object; end case; end Set_Member; package Object_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context, Element_Type_Access => Object_Mapper_Context_Access, Fields => Object_Field, Set_Member => Set_Member); JSON_Mapping : aliased Object_Mapper.Mapper; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into the <b>Output</b> -- JSON stream. Use the <b>Name</b> as the name of the JSON object. -- ----------------------- procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream'Class; Name : in String; Map : in Util.Beans.Objects.Maps.Map) is use type Ada.Containers.Count_Type; procedure Write (Name : in String; Value : in Util.Beans.Objects.Object); procedure Write (Name : in String; Value : in Util.Beans.Objects.Object) is begin Output.Start_Entity (Name => ""); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_Attribute (Name => "value", Value => Value); Output.End_Entity (Name => ""); end Write; begin if Map.Length > 0 then declare Iter : Util.Beans.Objects.Maps.Cursor := Map.First; begin Output.Start_Array (Name => Name); while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access); Util.Beans.Objects.Maps.Next (Iter); end loop; Output.End_Array (Name => Name); end; end if; end To_JSON; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into an XML stream. -- Returns the JSON string that contains a serialization of the object maps. -- ----------------------- function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is use type Ada.Containers.Count_Type; begin if Map.Length = 0 then return ""; end if; declare Buffer : aliased Util.Streams.Texts.Print_Stream; Output : Util.Serialize.IO.JSON.Output_Stream; begin Buffer.Initialize (Size => 10000); Output.Initialize (Buffer'Unchecked_Access); Output.Start_Document; To_JSON (Output, "params", Map); Output.End_Document; return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Buffer)); end; end To_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. The object map passed in <b>Map</b> can contain existing values. -- They will be overriden by the JSON values. -- ----------------------- procedure From_JSON (Content : in String; Map : in out Util.Beans.Objects.Maps.Map) is Parser : Util.Serialize.IO.JSON.Parser; Context : aliased Object_Mapper_Context; begin if Content'Length > 0 then Context.Map := Map'Unchecked_Access; Parser.Add_Mapping ("/params", JSON_Mapping'Access); Object_Mapper.Set_Context (Parser, Context'Unchecked_Access); Parser.Parse_String (Content); end if; end From_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- with their values. -- Returns the object map that was restored. -- ----------------------- function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is Result : Util.Beans.Objects.Maps.Map; begin From_JSON (Content, Result); return Result; end From_JSON; begin JSON_Mapping.Add_Mapping ("name", FIELD_NAME); JSON_Mapping.Add_Mapping ("value", FIELD_VALUE); end Util.Serialize.Tools;
Update TO_JSON to use a text buffer and configure the json output stream
Update TO_JSON to use a text buffer and configure the json output stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
28e6ac060724e0ddbc71936fe72429ac1dd97586
tests/natools-s_expressions-encodings-tests.adb
tests/natools-s_expressions-encodings-tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2013, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Test_Tools; package body Natools.S_Expressions.Encodings.Tests is procedure All_Tests (Report : in out NT.Reporter'Class) is begin Report.Section ("Encodings in S-expressions"); Hexadecimal_Test (Report); Base64_Test (Report); Report.End_Section; end All_Tests; procedure Hexadecimal_Test (Report : in out NT.Reporter'Class) is All_Octets : Atom (1 .. 256); begin for I in All_Octets'Range loop All_Octets (I) := Octet (I - All_Octets'First); end loop; declare Name : constant String := "Decoding upper-case hexadecimal encoded"; begin Test_Tools.Test_Atom (Report, Name, All_Octets, Decode_Hex (Encode_Hex (All_Octets, Upper))); exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding lower-case hexadecimal encoded"; begin Test_Tools.Test_Atom (Report, Name, All_Octets, Decode_Hex (Encode_Hex (All_Octets, Lower))); exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding garbage-laced text"; begin Test_Tools.Test_Atom (Report, Name, (16#01#, 16#23#, 16#45#, 16#67#, 16#89#, 16#AB#, 16#CD#, 16#EF#, 16#AB#, 16#CD#, 16#EF#), Decode_Hex (All_Octets)); exception when Error : others => Report.Report_Exception (Name, Error); end; end Hexadecimal_Test; procedure Base64_Test (Report : in out NT.Reporter'Class) is begin declare Name : constant String := "Decoding encoding of all octet triplets"; Success : Boolean := True; Expected : Atom (1 .. 3); begin for A in Octet loop Expected (1) := A; for B in Octet loop Expected (2) := B; for C in Octet loop Expected (3) := C; declare Found : constant Atom := Decode_Base64 (Encode_Base64 (Expected)); begin if Expected /= Found then if Success then Success := False; Report.Item (Name, NT.Fail); end if; Test_Tools.Dump_Atom (Report, Found, "Found"); Test_Tools.Dump_Atom (Report, Expected, "Expected"); end if; end; end loop; end loop; end loop; if Success then Report.Item (Name, NT.Success); end if; exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding encoding of all octet duets"; Success : Boolean := True; Expected : Atom (1 .. 2); begin for A in Octet loop Expected (1) := A; for B in Octet loop Expected (2) := B; declare Found : constant Atom := Decode_Base64 (Encode_Base64 (Expected)); begin if Expected /= Found then if Success then Success := False; Report.Item (Name, NT.Fail); end if; Test_Tools.Dump_Atom (Report, Found, "Found"); Test_Tools.Dump_Atom (Report, Expected, "Expected"); end if; end; end loop; end loop; if Success then Report.Item (Name, NT.Success); end if; exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding encoding of all single octets"; Success : Boolean := True; Expected : Atom (1 .. 1); begin for A in Octet loop Expected (1) := A; declare Found : constant Atom := Decode_Base64 (Encode_Base64 (Expected)); begin if Expected /= Found then if Success then Success := False; Report.Item (Name, NT.Fail); end if; Test_Tools.Dump_Atom (Report, Found, "Found"); Test_Tools.Dump_Atom (Report, Expected, "Expected"); end if; end; end loop; if Success then Report.Item (Name, NT.Success); end if; exception when Error : others => Report.Report_Exception (Name, Error); end; end Base64_Test; end Natools.S_Expressions.Encodings.Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2013-2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Exceptions; with Natools.S_Expressions.Test_Tools; package body Natools.S_Expressions.Encodings.Tests is procedure All_Tests (Report : in out NT.Reporter'Class) is begin Hexadecimal_Test (Report); Base64_Test (Report); end All_Tests; procedure Hexadecimal_Test (Report : in out NT.Reporter'Class) is All_Octets : Atom (1 .. 256); begin for I in All_Octets'Range loop All_Octets (I) := Octet (I - All_Octets'First); end loop; declare Name : constant String := "Decoding upper-case hexadecimal encoded"; begin Test_Tools.Test_Atom (Report, Name, All_Octets, Decode_Hex (Encode_Hex (All_Octets, Upper))); exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding lower-case hexadecimal encoded"; begin Test_Tools.Test_Atom (Report, Name, All_Octets, Decode_Hex (Encode_Hex (All_Octets, Lower))); exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding garbage-laced text"; begin Test_Tools.Test_Atom (Report, Name, (16#01#, 16#23#, 16#45#, 16#67#, 16#89#, 16#AB#, 16#CD#, 16#EF#, 16#AB#, 16#CD#, 16#EF#), Decode_Hex (All_Octets)); exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding an odd number of nibbles"; begin Test_Tools.Test_Atom (Report, Name, (16#45#, 16#56#, 16#70#), Decode_Hex (To_Atom ("45 56 7"))); exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decode_Hex with non-hex-digit"; Result : Octet; begin Result := Decode_Hex (180); Report.Item (Name, NT.Fail); Report.Info ("No exception raised. Result: " & Octet'Image (Result)); exception when Constraint_Error => Report.Item (Name, NT.Success); when Error : others => Report.Item (Name, NT.Fail); Report.Info ("Unexpected exception " & Ada.Exceptions.Exception_Name (Error) & " has been raised"); end; declare Name : constant String := "Overflow in Encode_Hex"; Result : Octet; begin Result := Encode_Hex (16, Lower); Report.Item (Name, NT.Fail); Report.Info ("No exception raised. Result: " & Octet'Image (Result)); exception when Constraint_Error => Report.Item (Name, NT.Success); when Error : others => Report.Item (Name, NT.Fail); Report.Info ("Unexpected exception " & Ada.Exceptions.Exception_Name (Error) & " has been raised"); end; end Hexadecimal_Test; procedure Base64_Test (Report : in out NT.Reporter'Class) is begin declare Name : constant String := "Decoding encoding of all octet triplets"; Success : Boolean := True; Expected : Atom (1 .. 3); begin for A in Octet loop Expected (1) := A; for B in Octet loop Expected (2) := B; for C in Octet loop Expected (3) := C; declare Found : constant Atom := Decode_Base64 (Encode_Base64 (Expected)); begin if Expected /= Found then if Success then Success := False; Report.Item (Name, NT.Fail); end if; Test_Tools.Dump_Atom (Report, Found, "Found"); Test_Tools.Dump_Atom (Report, Expected, "Expected"); end if; end; end loop; end loop; end loop; if Success then Report.Item (Name, NT.Success); end if; exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding encoding of all octet duets"; Success : Boolean := True; Expected : Atom (1 .. 2); begin for A in Octet loop Expected (1) := A; for B in Octet loop Expected (2) := B; declare Found : constant Atom := Decode_Base64 (Encode_Base64 (Expected)); begin if Expected /= Found then if Success then Success := False; Report.Item (Name, NT.Fail); end if; Test_Tools.Dump_Atom (Report, Found, "Found"); Test_Tools.Dump_Atom (Report, Expected, "Expected"); end if; end; end loop; end loop; if Success then Report.Item (Name, NT.Success); end if; exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decoding encoding of all single octets"; Success : Boolean := True; Expected : Atom (1 .. 1); begin for A in Octet loop Expected (1) := A; declare Found : constant Atom := Decode_Base64 (Encode_Base64 (Expected)); begin if Expected /= Found then if Success then Success := False; Report.Item (Name, NT.Fail); end if; Test_Tools.Dump_Atom (Report, Found, "Found"); Test_Tools.Dump_Atom (Report, Expected, "Expected"); end if; end; end loop; if Success then Report.Item (Name, NT.Success); end if; exception when Error : others => Report.Report_Exception (Name, Error); end; declare Name : constant String := "Decode_Base64 with non-base64-digit"; Result : Octet; begin Result := Decode_Base64 (127); Report.Item (Name, NT.Fail); Report.Info ("No exception raised. Result: " & Octet'Image (Result)); exception when Constraint_Error => Report.Item (Name, NT.Success); when Error : others => Report.Item (Name, NT.Fail); Report.Info ("Unexpected exception " & Ada.Exceptions.Exception_Name (Error) & " has been raised"); end; declare Name : constant String := "Overflow in Encode_Base64"; Result : Octet; begin Result := Encode_Base64 (64); Report.Item (Name, NT.Fail); Report.Info ("No exception raised. Result: " & Octet'Image (Result)); exception when Constraint_Error => Report.Item (Name, NT.Success); when Error : others => Report.Item (Name, NT.Fail); Report.Info ("Unexpected exception " & Ada.Exceptions.Exception_Name (Error) & " has been raised"); end; end Base64_Test; end Natools.S_Expressions.Encodings.Tests;
add more tests to reach complete coverage
s_expressions-encodings-tests: add more tests to reach complete coverage
Ada
isc
faelys/natools
58afe5e5e7df8c197e6357751e4986a8b9e1e2bd
src/gen-model-tables.adb
src/gen-model-tables.adb
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; with Util.Log.Loggers; package body Gen.Model.Tables is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables"); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then if Length (From.Sql_Type) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Type); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return T.Get_Value ("name"); end; elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access := null; Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, "."); begin if Pos = 0 then Result := Gen.Model.Mappings.Find_Type (From.Type_Name); end if; if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then Log.Debug ("Found enum"); end if; if Result = null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin -- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); -- if O.Type_Mapping = null then -- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); -- end if; null; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Create a table association with the given name and add it to the table. -- ------------------------------ procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access) is begin Assoc := new Association_Definition; Assoc.Name := Name; Assoc.Number := Table.Members.Get_Count; Assoc.Table := Table'Unchecked_Access; Table.Members.Append (Assoc.all'Access); Table.Has_Associations := True; end Add_Association; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "operations" then return From.Operations_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; with Util.Log.Loggers; package body Gen.Model.Tables is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables"); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then if Length (From.Sql_Type) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Type); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return T.Get_Value ("name"); end; elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access := null; Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, "."); begin if Pos = 0 then Result := Gen.Model.Mappings.Find_Type (From.Type_Name); end if; if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then Log.Debug ("Found enum"); end if; if Result = null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin -- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); -- if O.Type_Mapping = null then -- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); -- end if; null; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Create a table association with the given name and add it to the table. -- ------------------------------ procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access) is begin Assoc := new Association_Definition; Assoc.Name := Name; Assoc.Number := Table.Members.Get_Count; Assoc.Table := Table'Unchecked_Access; Assoc.Sql_Name := Name; Table.Members.Append (Assoc.all'Access); Table.Has_Associations := True; end Add_Association; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "operations" then return From.Operations_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
Set the association sql name from the association name
Set the association sql name from the association name
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
b46668d706c3bbf7d77273ffe6fa54e7531a6e3c
src/wiki-render-text.adb
src/wiki-render-text.adb
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; end Render_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Document : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is begin Document.Open_Paragraph; if Title'Length /= 0 then Document.Output.Write (Title); end if; Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; -- if Length (Alt) > 0 then -- Document.Output.Write (Alt); -- end if; -- if Length (Description) > 0 then -- Document.Output.Write (Description); -- end if; -- Document.Output.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Add_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.Nodes.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.Nodes.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Renderer) is begin Document.Close_Paragraph; end Finish; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; end Render_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Document : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is begin Document.Open_Paragraph; if Title'Length /= 0 then Document.Output.Write (Title); end if; Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; -- if Length (Alt) > 0 then -- Document.Output.Write (Alt); -- end if; -- if Length (Description) > 0 then -- Document.Output.Write (Description); -- end if; -- Document.Output.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Html_Tag; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Add_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Renderer) is begin Document.Close_Paragraph; end Finish; end Wiki.Render.Text;
Move the Html_Tag type from Wiki.Nodes to Wiki package
Move the Html_Tag type from Wiki.Nodes to Wiki package
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ca7c9dc004e6838cef1c0a963d1b0e0b7b1aa4d8
src/asf-utils.adb
src/asf-utils.adb
----------------------------------------------------------------------- -- html -- ASF HTML Components -- 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. ----------------------------------------------------------------------- package body ASF.Utils is TITLE_ATTR : aliased constant String := "title"; STYLE_ATTR : aliased constant String := "style"; STYLE_CLASS_ATTR : aliased constant String := "styleClass"; DIR_ATTR : aliased constant String := "dir"; LANG_ATTR : aliased constant String := "lang"; ACCESS_KEY_ATTR : aliased constant String := "accesskey"; ON_BLUR_ATTR : aliased constant String := "onblur"; ON_CLICK_ATTR : aliased constant String := "onclick"; ON_DBLCLICK_ATTR : aliased constant String := "ondblclick"; ON_FOCUS_ATTR : aliased constant String := "onfocus"; ON_KEYDOWN_ATTR : aliased constant String := "onkeydown"; ON_KEYUP_ATTR : aliased constant String := "onkeyup"; ON_MOUSE_DOWN_ATTR : aliased constant String := "onmousedown"; ON_MOUSE_MOVE_ATTR : aliased constant String := "onmousemove"; ON_MOUSE_OUT_ATTR : aliased constant String := "onmouseout"; ON_MOUSE_OVER_ATTR : aliased constant String := "onmouseover"; ON_MOUSE_UP_ATTR : aliased constant String := "onmouseup"; ON_CHANGE_ATTR : aliased constant String := "onchange"; ON_RESET_ATTR : aliased constant String := "onreset"; ON_SUBMIT_ATTR : aliased constant String := "onsubmit"; ENCTYPE_ATTR : aliased constant String := "enctype"; ON_LOAD_ATTR : aliased constant String := "onload"; ON_UNLOAD_ATTR : aliased constant String := "onunload"; TABINDEX_ATTR : aliased constant String := "tabindex"; AUTOCOMPLETE_ATTR : aliased constant String := "autocomplete"; SIZE_ATTR : aliased constant String := "size"; MAXLENGTH_ATTR : aliased constant String := "maxlength"; ALT_ATTR : aliased constant String := "alt"; DISABLED_ATTR : aliased constant String := "disabled"; READONLY_ATTR : aliased constant String := "readonly"; PLACEHOLDER_ATTR : aliased constant String := "placeholder"; PATTERN_ATTR : aliased constant String := "pattern"; AUTOFOCUS_ATTR : aliased constant String := "autofocus"; LIST_ATTR : aliased constant String := "list"; FORMENCTYPE_ATTR : aliased constant String := "formenctype"; FORMMETHOD_ATTR : aliased constant String := "formmethod"; FORMACTION_ATTR : aliased constant String := "formaction"; FORMTARGET_ATTR : aliased constant String := "formtarget"; ACCEPT_ATTR : aliased constant String := "accept"; ROWS_ATTR : aliased constant String := "rows"; COLS_ATTR : aliased constant String := "cols"; CHARSET_ATTR : aliased constant String := "charset"; SHAPE_ATTR : aliased constant String := "shape"; REV_ATTR : aliased constant String := "rev"; COORDS_ATTR : aliased constant String := "coords"; TARGET_ATTR : aliased constant String := "target"; HREFLANG_ATTR : aliased constant String := "hreflang"; -- ------------------------------ -- Add in the <b>names</b> set, the basic text attributes that can be set -- on HTML elements (dir, lang, style, title). -- ------------------------------ procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (STYLE_CLASS_ATTR'Access); Names.Insert (TITLE_ATTR'Access); Names.Insert (DIR_ATTR'Access); Names.Insert (LANG_ATTR'Access); Names.Insert (STYLE_ATTR'Access); end Set_Text_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the onXXX attributes that can be set -- on HTML elements (accesskey, tabindex, onXXX). -- ------------------------------ procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ACCESS_KEY_ATTR'Access); Names.Insert (TABINDEX_ATTR'Access); Names.Insert (ON_BLUR_ATTR'Access); Names.Insert (ON_MOUSE_UP_ATTR'Access); Names.Insert (ON_MOUSE_OVER_ATTR'Access); Names.Insert (ON_MOUSE_OUT_ATTR'Access); Names.Insert (ON_MOUSE_MOVE_ATTR'Access); Names.Insert (ON_MOUSE_DOWN_ATTR'Access); Names.Insert (ON_KEYUP_ATTR'Access); Names.Insert (ON_KEYDOWN_ATTR'Access); Names.Insert (ON_FOCUS_ATTR'Access); Names.Insert (ON_DBLCLICK_ATTR'Access); Names.Insert (ON_CLICK_ATTR'Access); Names.Insert (ON_CHANGE_ATTR'Access); end Set_Interactive_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the size attributes that can be set -- on HTML elements. -- ------------------------------ procedure Set_Input_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (SIZE_ATTR'Access); Names.Insert (AUTOCOMPLETE_ATTR'Access); Names.Insert (MAXLENGTH_ATTR'Access); Names.Insert (ALT_ATTR'Access); Names.Insert (DISABLED_ATTR'Access); Names.Insert (READONLY_ATTR'Access); Names.Insert (PLACEHOLDER_ATTR'Access); Names.Insert (PATTERN_ATTR'Access); Names.Insert (AUTOFOCUS_ATTR'Access); Names.Insert (LIST_ATTR'Access); Names.Insert (FORMENCTYPE_ATTR'Access); Names.Insert (FORMMETHOD_ATTR'Access); Names.Insert (FORMACTION_ATTR'Access); Names.Insert (FORMTARGET_ATTR'Access); end Set_Input_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the size attributes that can be set -- on <textarea> elements. -- ------------------------------ procedure Set_Textarea_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ROWS_ATTR'Access); Names.Insert (COLS_ATTR'Access); end Set_Textarea_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the online and onunload attributes that can be set -- on <body> elements. -- ------------------------------ procedure Set_Body_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ON_LOAD_ATTR'Access); Names.Insert (ON_UNLOAD_ATTR'Access); end Set_Body_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the dir, lang attributes that can be set -- on <head> elements. -- ------------------------------ procedure Set_Head_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (DIR_ATTR'Access); Names.Insert (LANG_ATTR'Access); end Set_Head_Attributes; -------------------- -- Add in the <b>names</b> set, the onreset and onsubmit attributes that can be set -- on <form> elements. -- ------------------------------ procedure Set_Form_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ON_RESET_ATTR'Access); Names.Insert (ON_SUBMIT_ATTR'Access); Names.Insert (ENCTYPE_ATTR'Access); end Set_Form_Attributes; -------------------- -- Add in the <b>names</b> set, the attributes which are specific to a link. -- ------------------------------ procedure Set_Link_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (CHARSET_ATTR'Access); Names.Insert (SHAPE_ATTR'Access); Names.Insert (REV_ATTR'Access); Names.Insert (COORDS_ATTR'Access); Names.Insert (TARGET_ATTR'Access); Names.Insert (HREFLANG_ATTR'Access); end Set_Link_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the attributes which are specific to an input file. -- ------------------------------ procedure Set_File_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ACCEPT_ATTR'Access); end Set_File_Attributes; end ASF.Utils;
----------------------------------------------------------------------- -- html -- ASF HTML Components -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ASF.Utils is TITLE_ATTR : aliased constant String := "title"; STYLE_ATTR : aliased constant String := "style"; STYLE_CLASS_ATTR : aliased constant String := "styleClass"; DIR_ATTR : aliased constant String := "dir"; LANG_ATTR : aliased constant String := "lang"; ACCESS_KEY_ATTR : aliased constant String := "accesskey"; ON_BLUR_ATTR : aliased constant String := "onblur"; ON_CLICK_ATTR : aliased constant String := "onclick"; ON_DBLCLICK_ATTR : aliased constant String := "ondblclick"; ON_FOCUS_ATTR : aliased constant String := "onfocus"; ON_KEYDOWN_ATTR : aliased constant String := "onkeydown"; ON_KEYUP_ATTR : aliased constant String := "onkeyup"; ON_MOUSE_DOWN_ATTR : aliased constant String := "onmousedown"; ON_MOUSE_MOVE_ATTR : aliased constant String := "onmousemove"; ON_MOUSE_OUT_ATTR : aliased constant String := "onmouseout"; ON_MOUSE_OVER_ATTR : aliased constant String := "onmouseover"; ON_MOUSE_UP_ATTR : aliased constant String := "onmouseup"; ON_CHANGE_ATTR : aliased constant String := "onchange"; ON_RESET_ATTR : aliased constant String := "onreset"; ON_SUBMIT_ATTR : aliased constant String := "onsubmit"; ENCTYPE_ATTR : aliased constant String := "enctype"; ON_LOAD_ATTR : aliased constant String := "onload"; ON_UNLOAD_ATTR : aliased constant String := "onunload"; TABINDEX_ATTR : aliased constant String := "tabindex"; AUTOCOMPLETE_ATTR : aliased constant String := "autocomplete"; SIZE_ATTR : aliased constant String := "size"; MAXLENGTH_ATTR : aliased constant String := "maxlength"; ALT_ATTR : aliased constant String := "alt"; DISABLED_ATTR : aliased constant String := "disabled"; DIRNAME_ATTR : aliased constant String := "dirname"; READONLY_ATTR : aliased constant String := "readonly"; PLACEHOLDER_ATTR : aliased constant String := "placeholder"; PATTERN_ATTR : aliased constant String := "pattern"; AUTOFOCUS_ATTR : aliased constant String := "autofocus"; LIST_ATTR : aliased constant String := "list"; FORMENCTYPE_ATTR : aliased constant String := "formenctype"; FORMMETHOD_ATTR : aliased constant String := "formmethod"; FORMACTION_ATTR : aliased constant String := "formaction"; FORMTARGET_ATTR : aliased constant String := "formtarget"; WRAP_ATTR : aliased constant String := "wrap"; ACCEPT_ATTR : aliased constant String := "accept"; ROWS_ATTR : aliased constant String := "rows"; COLS_ATTR : aliased constant String := "cols"; CHARSET_ATTR : aliased constant String := "charset"; SHAPE_ATTR : aliased constant String := "shape"; REV_ATTR : aliased constant String := "rev"; COORDS_ATTR : aliased constant String := "coords"; TARGET_ATTR : aliased constant String := "target"; HREFLANG_ATTR : aliased constant String := "hreflang"; -- ------------------------------ -- Add in the <b>names</b> set, the basic text attributes that can be set -- on HTML elements (dir, lang, style, title). -- ------------------------------ procedure Set_Text_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (STYLE_CLASS_ATTR'Access); Names.Insert (TITLE_ATTR'Access); Names.Insert (DIR_ATTR'Access); Names.Insert (LANG_ATTR'Access); Names.Insert (STYLE_ATTR'Access); end Set_Text_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the onXXX attributes that can be set -- on HTML elements (accesskey, tabindex, onXXX). -- ------------------------------ procedure Set_Interactive_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ACCESS_KEY_ATTR'Access); Names.Insert (TABINDEX_ATTR'Access); Names.Insert (ON_BLUR_ATTR'Access); Names.Insert (ON_MOUSE_UP_ATTR'Access); Names.Insert (ON_MOUSE_OVER_ATTR'Access); Names.Insert (ON_MOUSE_OUT_ATTR'Access); Names.Insert (ON_MOUSE_MOVE_ATTR'Access); Names.Insert (ON_MOUSE_DOWN_ATTR'Access); Names.Insert (ON_KEYUP_ATTR'Access); Names.Insert (ON_KEYDOWN_ATTR'Access); Names.Insert (ON_FOCUS_ATTR'Access); Names.Insert (ON_DBLCLICK_ATTR'Access); Names.Insert (ON_CLICK_ATTR'Access); Names.Insert (ON_CHANGE_ATTR'Access); end Set_Interactive_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the size attributes that can be set -- on HTML elements. -- ------------------------------ procedure Set_Input_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (SIZE_ATTR'Access); Names.Insert (AUTOCOMPLETE_ATTR'Access); Names.Insert (MAXLENGTH_ATTR'Access); Names.Insert (ALT_ATTR'Access); Names.Insert (DISABLED_ATTR'Access); Names.Insert (READONLY_ATTR'Access); Names.Insert (PLACEHOLDER_ATTR'Access); Names.Insert (PATTERN_ATTR'Access); Names.Insert (AUTOFOCUS_ATTR'Access); Names.Insert (LIST_ATTR'Access); Names.Insert (FORMENCTYPE_ATTR'Access); Names.Insert (FORMMETHOD_ATTR'Access); Names.Insert (FORMACTION_ATTR'Access); Names.Insert (FORMTARGET_ATTR'Access); end Set_Input_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the size attributes that can be set -- on <textarea> elements. -- ------------------------------ procedure Set_Textarea_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (AUTOFOCUS_ATTR'Access); Names.Insert (COLS_ATTR'Access); Names.Insert (DIRNAME_ATTR'Access); Names.Insert (DISABLED_ATTR'Access); Names.Insert (MAXLENGTH_ATTR'Access); Names.Insert (PLACEHOLDER_ATTR'Access); Names.Insert (READONLY_ATTR'Access); Names.Insert (ROWS_ATTR'Access); Names.Insert (WRAP_ATTR'Access); end Set_Textarea_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the online and onunload attributes that can be set -- on <body> elements. -- ------------------------------ procedure Set_Body_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ON_LOAD_ATTR'Access); Names.Insert (ON_UNLOAD_ATTR'Access); end Set_Body_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the dir, lang attributes that can be set -- on <head> elements. -- ------------------------------ procedure Set_Head_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (DIR_ATTR'Access); Names.Insert (LANG_ATTR'Access); end Set_Head_Attributes; -------------------- -- Add in the <b>names</b> set, the onreset and onsubmit attributes that can be set -- on <form> elements. -- ------------------------------ procedure Set_Form_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ON_RESET_ATTR'Access); Names.Insert (ON_SUBMIT_ATTR'Access); Names.Insert (ENCTYPE_ATTR'Access); end Set_Form_Attributes; -------------------- -- Add in the <b>names</b> set, the attributes which are specific to a link. -- ------------------------------ procedure Set_Link_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (CHARSET_ATTR'Access); Names.Insert (SHAPE_ATTR'Access); Names.Insert (REV_ATTR'Access); Names.Insert (COORDS_ATTR'Access); Names.Insert (TARGET_ATTR'Access); Names.Insert (HREFLANG_ATTR'Access); end Set_Link_Attributes; -- ------------------------------ -- Add in the <b>names</b> set, the attributes which are specific to an input file. -- ------------------------------ procedure Set_File_Attributes (Names : in out Util.Strings.String_Set.Set) is begin Names.Insert (ACCEPT_ATTR'Access); end Set_File_Attributes; end ASF.Utils;
Fix Set_Textarea_Attributes to take into account more attributes for the HTML textarea
Fix Set_Textarea_Attributes to take into account more attributes for the HTML textarea
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
8f45d1c26db082e1e1589b017c0c249f4a739765
demo/spinner.adb
demo/spinner.adb
-- Simple Lumen demo/test program, using earliest incomplete library. with Lumen.Window; with Lumen.Events.Animate; with GL; with GLU; procedure Spinner is --------------------------------------------------------------------------- -- Rotation wraps around at this point, in degrees Max_Rotation : constant := 359; -- Traditional cinema framrate, in frames per second Framerate : constant := 24; --------------------------------------------------------------------------- Win : Lumen.Window.Handle; Event : Lumen.Events.Event_Data; Wide : Natural := 400; High : Natural := 400; Rotation : Natural := 0; --------------------------------------------------------------------------- Program_Exit : exception; --------------------------------------------------------------------------- -- Set or reset the window view parameters procedure Set_View (W, H : in Natural) is use GL; use GLU; Aspect : GLdouble; begin -- Set_View -- Viewport dimensions glViewport (0, 0, GLsizei (W), GLsizei (H)); -- Set up the projection matrix based on the window's shape--wider than -- high, or higher than wide glMatrixMode (GL_PROJECTION); glLoadIdentity; if W <= H then Aspect := GLdouble (H) / GLdouble (W); gluOrtho2D (-2.0, 2.0, -2.0 * Aspect, 2.0 * Aspect); else Aspect := GLdouble (W) / GLdouble (H); gluOrtho2D (-2.0 * Aspect, 2.0 * Aspect, -2.0, 2.0); end if; end Set_View; --------------------------------------------------------------------------- -- Draw our scene procedure Draw is use GL; begin -- Draw -- Set a black background glClearColor (0.0, 0.0, 0.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); -- Draw a hideous orange square glColor3f (1.0, 1.0, 0.5); glBegin (GL_POLYGON); begin glVertex2f (-1.0, -1.0); glVertex2f (-1.0, 1.0); glVertex2f ( 1.0, 1.0); glVertex2f ( 1.0, -1.0); end; glEnd; -- Rotate the square around the Z axis by the current amount glMatrixMode (GL_MODELVIEW); glLoadIdentity; glRotated (GLdouble (Rotation), 0.0, 0.0, -1.0); glFlush; -- Now show it Lumen.Window.Swap (Win); end Draw; --------------------------------------------------------------------------- -- Simple event handler routine for keypresses and close-window events procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin -- Quit_Handler raise Program_Exit; end Quit_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Exposed events procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is begin -- Expose_Handler Draw; end Expose_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Resized events procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is begin -- Resize_Handler Wide := Event.Resize_Data.Width; High := Event.Resize_Data.Height; Set_View (Wide, High); Draw; end Resize_Handler; --------------------------------------------------------------------------- -- Our draw-a-frame routine, should get called FPS times a second procedure New_Frame is begin -- New_Frame if Rotation >= Max_Rotation then Rotation := 0; else Rotation := Rotation + 1; end if; Draw; end New_Frame; --------------------------------------------------------------------------- begin -- Spinner -- Create Lumen window, accepting most defaults; turn double buffering off -- for simplicity Win := Lumen.Window.Create (Name => "Spinning Square Demo", Width => Wide, Height => High, Events => (Lumen.Window.Want_Key_Press => True, Lumen.Window.Want_Exposure => True, others => False)); -- Set up the viewport and scene parameters Set_View (Wide, High); -- Enter the event loop declare use Lumen.Events; begin Animate.Select_Events (Win => Win, Calls => (Key_Press => Quit_Handler'Unrestricted_Access, Exposed => Expose_Handler'Unrestricted_Access, Resized => Resize_Handler'Unrestricted_Access, Close_Window => Quit_Handler'Unrestricted_Access, others => No_Callback), FPS => Framerate, Frame => New_Frame'Unrestricted_Access); end; exception when Program_Exit => null; -- just exit this block, which terminates the app end Spinner;
-- Simple Lumen demo/test program, using earliest incomplete library. with Lumen.Window; with Lumen.Events.Animate; with GL; with GLU; procedure Spinner is --------------------------------------------------------------------------- -- Rotation wraps around at this point, in degrees Max_Rotation : constant := 359; -- Traditional cinema framrate, in frames per second Framerate : constant := 24; --------------------------------------------------------------------------- Win : Lumen.Window.Handle; Event : Lumen.Events.Event_Data; Wide : Natural := 400; High : Natural := 400; Rotation : Natural := 0; --------------------------------------------------------------------------- Program_Exit : exception; --------------------------------------------------------------------------- -- Set or reset the window view parameters procedure Set_View (W, H : in Natural) is use GL; use GLU; Aspect : GLdouble; begin -- Set_View -- Viewport dimensions glViewport (0, 0, GLsizei (W), GLsizei (H)); -- Set up the projection matrix based on the window's shape--wider than -- high, or higher than wide glMatrixMode (GL_PROJECTION); glLoadIdentity; if W <= H then Aspect := GLdouble (H) / GLdouble (W); gluOrtho2D (-2.0, 2.0, -2.0 * Aspect, 2.0 * Aspect); else Aspect := GLdouble (W) / GLdouble (H); gluOrtho2D (-2.0 * Aspect, 2.0 * Aspect, -2.0, 2.0); end if; end Set_View; --------------------------------------------------------------------------- -- Draw our scene procedure Draw is use GL; begin -- Draw -- Set a black background glClearColor (0.0, 0.0, 0.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); glBegin (GL_POLYGON); begin glColor3f (1.0, 0.0, 0.0); glVertex2f (-1.0, -1.0); glColor3f (1.0, 0.0, 0.0); glVertex2f (-1.0, 1.0); glColor3f (1.0, 1.0, 0.0); glVertex2f ( 1.0, 1.0); glColor3f (1.0, 1.0, 0.0); glVertex2f ( 1.0, -1.0); end; glEnd; -- Rotate the square around the Z axis by the current amount glMatrixMode (GL_MODELVIEW); glLoadIdentity; glRotated (GLdouble (Rotation), 0.0, 0.0, -1.0); glFlush; -- Now show it Lumen.Window.Swap (Win); end Draw; --------------------------------------------------------------------------- -- Simple event handler routine for keypresses and close-window events procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is begin -- Quit_Handler raise Program_Exit; end Quit_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Exposed events procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is begin -- Expose_Handler Draw; end Expose_Handler; --------------------------------------------------------------------------- -- Simple event handler routine for Resized events procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is begin -- Resize_Handler Wide := Event.Resize_Data.Width; High := Event.Resize_Data.Height; Set_View (Wide, High); Draw; end Resize_Handler; --------------------------------------------------------------------------- -- Our draw-a-frame routine, should get called FPS times a second procedure New_Frame is begin -- New_Frame if Rotation >= Max_Rotation then Rotation := 0; else Rotation := Rotation + 1; end if; Draw; end New_Frame; --------------------------------------------------------------------------- begin -- Spinner -- Create Lumen window, accepting most defaults; turn double buffering off -- for simplicity Win := Lumen.Window.Create (Name => "Spinning Square Demo", Width => Wide, Height => High, Events => (Lumen.Window.Want_Key_Press => True, Lumen.Window.Want_Exposure => True, others => False)); -- Set up the viewport and scene parameters Set_View (Wide, High); -- Enter the event loop declare use Lumen.Events; begin Animate.Select_Events (Win => Win, Calls => (Key_Press => Quit_Handler'Unrestricted_Access, Exposed => Expose_Handler'Unrestricted_Access, Resized => Resize_Handler'Unrestricted_Access, Close_Window => Quit_Handler'Unrestricted_Access, others => No_Callback), FPS => Framerate, Frame => New_Frame'Unrestricted_Access); end; exception when Program_Exit => null; -- just exit this block, which terminates the app end Spinner;
Add a little color to our square to improve visual appeal
Add a little color to our square to improve visual appeal
Ada
isc
darkestkhan/lumen,darkestkhan/lumen2
d388bcd155cb31daecae81f7f692480c40201d5b
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Objects; with ADO.Sessions; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; private with Ada.Strings.Unbounded; -- == Events == -- The *workspaces* module provides several events that are posted when some action are performed. -- -- === invite-user === -- This event is posted when an invitation is created for a user. The event can be used to -- send the associated invitation email to the invitee. The event contains the following -- attributes: -- -- key -- email -- name -- message -- inviter -- -- === accept-invitation === -- This event is posted when an invitation is accepted by a user. package AWA.Workspaces.Modules is subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array; Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- The configuration parameter that defines the list of permissions to grant -- to a user when his workspace is created. PARAM_PERMISSIONS_LIST : constant String := "permissions_list"; -- Permission to create a workspace. package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create"); package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Workspace_Module; Props : in ASF.Applications.Config); -- Get the list of permissions for the workspace owner. function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array; -- Get the workspace module. function Get_Workspace_Module return Workspace_Module_Access; -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); -- Add a list of permissions for all the users of the workspace that have the appropriate -- role. Workspace members will be able to access the given database entity for the -- specified list of permissions. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; List : in Security.Permissions.Permission_Index_Array); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; -- The list of permissions to grant to a user who creates the workspace. Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Objects; with ADO.Sessions; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; private with Ada.Strings.Unbounded; -- == Events == -- The *workspaces* module provides several events that are posted when some action are performed. -- -- === invite-user === -- This event is posted when an invitation is created for a user. The event can be used to -- send the associated invitation email to the invitee. The event contains the following -- attributes: -- -- key -- email -- name -- message -- inviter -- -- === accept-invitation === -- This event is posted when an invitation is accepted by a user. package AWA.Workspaces.Modules is subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array; Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- The configuration parameter that defines the list of permissions to grant -- to a user when his workspace is created. PARAM_PERMISSIONS_LIST : constant String := "permissions_list"; -- Permission to create a workspace. package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create"); package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Workspace_Module; Props : in ASF.Applications.Config); -- Get the list of permissions for the workspace owner. function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array; -- Get the workspace module. function Get_Workspace_Module return Workspace_Module_Access; -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Create a workspace for the user. procedure Create_Workspace (Module : in Workspace_Module; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); -- Add a list of permissions for all the users of the workspace that have the appropriate -- role. Workspace members will be able to access the given database entity for the -- specified list of permissions. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; List : in Security.Permissions.Permission_Index_Array); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; -- The list of permissions to grant to a user who creates the workspace. Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Workspaces.Modules;
Declare the Create_Workspace procedure
Declare the Create_Workspace procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
10e74f0a9cfb917b8d568be7410f7d1b75c8e513
src/util-beans-objects-enums.adb
src/util-beans-objects-enums.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Enums -- Helper conversion for discrete types -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body Util.Beans.Objects.Enums is use Ada.Characters.Conversions; Value_Range : constant Long_Long_Integer := T'Pos (T'Last) - T'Pos (T'First) + 1; -- ------------------------------ -- Integer Type -- ------------------------------ type Enum_Type is new Int_Type with null record; -- Get the type name overriding function Get_Name (Type_Def : in Enum_Type) return String; overriding function To_String (Type_Def : in Enum_Type; Value : in Object_Value) return String; -- ------------------------------ -- Get the type name -- ------------------------------ overriding function Get_Name (Type_Def : Enum_Type) return String is pragma Unreferenced (Type_Def); begin return "Enum"; end Get_Name; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ overriding function To_String (Type_Def : in Enum_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return T'Image (T'Val (Value.Int_Value)); end To_String; Value_Type : aliased constant Enum_Type := Enum_Type '(others => <>); -- ------------------------------ -- Create an object from the given value. -- ------------------------------ function To_Object (Value : in T) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_INTEGER, Int_Value => Long_Long_Integer (T'Pos (Value))), Type_Def => Value_Type'Access); end To_Object; -- ------------------------------ -- Convert the object into a value. -- Raises Constraint_Error if the object cannot be converter to the target type. -- ------------------------------ function To_Value (Value : in Util.Beans.Objects.Object) return T is begin case Value.V.Of_Type is when TYPE_INTEGER => if ROUND_VALUE then return T'Val (Value.V.Int_Value mod Value_Range); else return T'Val (Value.V.Int_Value); end if; when TYPE_BOOLEAN => return T'Val (Boolean'Pos (Value.V.Bool_Value)); when TYPE_FLOAT => if ROUND_VALUE then return T'Val (To_Long_Long_Integer (Value) mod Value_Range); else return T'Val (To_Long_Long_Integer (Value)); end if; when TYPE_STRING => if Value.V.String_Proxy = null then raise Constraint_Error with "The object value is null"; end if; return T'Value (Value.V.String_Proxy.Value); when TYPE_WIDE_STRING => if Value.V.Wide_Proxy = null then raise Constraint_Error with "The object value is null"; end if; return T'Value (To_String (Value.V.Wide_Proxy.Value)); when TYPE_NULL => raise Constraint_Error with "The object value is null"; when TYPE_TIME => raise Constraint_Error with "Cannot convert a date into a discrete type"; when TYPE_BEAN => raise Constraint_Error with "Cannot convert a bean into a discrete type"; end case; end To_Value; end Util.Beans.Objects.Enums;
----------------------------------------------------------------------- -- Util.Beans.Objects.Enums -- Helper conversion for discrete types -- Copyright (C) 2010, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body Util.Beans.Objects.Enums is use Ada.Characters.Conversions; Value_Range : constant Long_Long_Integer := T'Pos (T'Last) - T'Pos (T'First) + 1; -- ------------------------------ -- Integer Type -- ------------------------------ type Enum_Type is new Int_Type with null record; -- Get the type name overriding function Get_Name (Type_Def : in Enum_Type) return String; overriding function To_String (Type_Def : in Enum_Type; Value : in Object_Value) return String; -- ------------------------------ -- Get the type name -- ------------------------------ overriding function Get_Name (Type_Def : Enum_Type) return String is pragma Unreferenced (Type_Def); begin return "Enum"; end Get_Name; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ overriding function To_String (Type_Def : in Enum_Type; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return T'Image (T'Val (Value.Int_Value)); end To_String; Value_Type : aliased constant Enum_Type := Enum_Type '(null record); -- ------------------------------ -- Create an object from the given value. -- ------------------------------ function To_Object (Value : in T) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_INTEGER, Int_Value => Long_Long_Integer (T'Pos (Value))), Type_Def => Value_Type'Access); end To_Object; -- ------------------------------ -- Convert the object into a value. -- Raises Constraint_Error if the object cannot be converter to the target type. -- ------------------------------ function To_Value (Value : in Util.Beans.Objects.Object) return T is begin case Value.V.Of_Type is when TYPE_INTEGER => if ROUND_VALUE then return T'Val (Value.V.Int_Value mod Value_Range); else return T'Val (Value.V.Int_Value); end if; when TYPE_BOOLEAN => return T'Val (Boolean'Pos (Value.V.Bool_Value)); when TYPE_FLOAT => if ROUND_VALUE then return T'Val (To_Long_Long_Integer (Value) mod Value_Range); else return T'Val (To_Long_Long_Integer (Value)); end if; when TYPE_STRING => if Value.V.String_Proxy = null then raise Constraint_Error with "The object value is null"; end if; return T'Value (Value.V.String_Proxy.Value); when TYPE_WIDE_STRING => if Value.V.Wide_Proxy = null then raise Constraint_Error with "The object value is null"; end if; return T'Value (To_String (Value.V.Wide_Proxy.Value)); when TYPE_NULL => raise Constraint_Error with "The object value is null"; when TYPE_TIME => raise Constraint_Error with "Cannot convert a date into a discrete type"; when TYPE_BEAN => raise Constraint_Error with "Cannot convert a bean into a discrete type"; end case; end To_Value; end Util.Beans.Objects.Enums;
Fix new GNAT compilation warning in initialization records: use null record
Fix new GNAT compilation warning in initialization records: use null record
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6a589d0d4420c6f7dd974dcb5789c2025663f9c5
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_fk = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Modules.Get; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; end AWA.Workspaces.Modules;
Update the implementation according to the UML model
Update the implementation according to the UML model
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
d472cd1d50274faebee131083e812aa9b69a6d3d
mat/src/mat-readers-marshaller.ads
mat/src/mat-readers-marshaller.ads
----------------------------------------------------------------------- -- Marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; -- -- function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); -- -- function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); -- -- function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); -- -- function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Marshaller -- Marshalling of data in communication buffer -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; -- -- function Get_Target_Size is new Get_Target_Value (MAT.Types.Target_Size); -- -- function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); -- -- function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); -- -- function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
Document Get_Uint16
Document Get_Uint16
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
48e87bc75ccd7dff4c0217f5586b5c4fda85b8e7
src/mysql/ado-drivers-connections-mysql.adb
src/mysql/ado-drivers-connections-mysql.adb
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Mysql; with ADO.Schemas.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create query statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create query statement {0}: connection is closed", Query); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create delete statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create insert statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create update statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Result : char; begin Result := mysql_commit (Database.Server); if Result /= nul then raise DB_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is Result : char; begin Result := mysql_rollback (Database.Server); if Result /= nul then raise DB_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Mysql.Load_Schema (Database, Schema); end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Error ("Database connection is not open"); raise Connection_Error with "Database connection is closed"; end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= null then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Server : Mysql_Access; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), To_String (Config.Server), To_String (Config.Database)); if Config.Get_Property ("password") = "" then Log.Debug ("MySQL connection with user={0}", Config.Get_Property ("user")); else Log.Debug ("MySQL connection with user={0} password=XXXXXXXX", Config.Get_Property ("user")); end if; Connection := mysql_init (null); Server := mysql_real_connect (Connection, ADO.C.To_C (Host), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message); mysql_close (Connection); raise Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); procedure Configure (Name, Item : in Util.Properties.Value) is Value : constant String := To_String (Item); begin if Name = "encoding" then Database.Execute ("SET NAMES " & Value); Database.Execute ("SET CHARACTER SET " & Value); Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'"); Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'"); elsif Name /= "user" and Name /= "password" then Database.Execute ("SET " & To_String (Name) & "='" & Value & "'"); end if; end Configure; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Server; Database.Name := Config.Database; -- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands. -- Typical configuration includes: -- encoding=utf8 -- collation_connection=utf8_general_ci Config.Properties.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; end ADO.Drivers.Connections.Mysql;
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Mysql; with ADO.Schemas.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create query statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create query statement {0}: connection is closed", Query); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create delete statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create insert statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin if Database.Server = null then Log.Warn ("Cannot create update statement on table {0}: connection is closed", Table.Table.all); raise Connection_Error with "Database connection is closed"; end if; return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Result : char; begin Result := mysql_commit (Database.Server); if Result /= nul then raise DB_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is Result : char; begin Result := mysql_rollback (Database.Server); if Result /= nul then raise DB_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Mysql.Load_Schema (Database, Schema); end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Error ("Database connection is not open"); raise Connection_Error with "Database connection is closed"; end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= null then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is Host : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Server : Mysql_Access; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), To_String (Config.Server), To_String (Config.Database)); if Config.Get_Property ("password") = "" then Log.Debug ("MySQL connection with user={0}", Config.Get_Property ("user")); else Log.Debug ("MySQL connection with user={0} password=XXXXXXXX", Config.Get_Property ("user")); end if; Connection := mysql_init (null); Server := mysql_real_connect (Connection, ADO.C.To_C (Host), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.Log_URI), Message); mysql_close (Connection); raise Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); procedure Configure (Name, Item : in Util.Properties.Value) is Value : constant String := To_String (Item); begin if Name = "encoding" then Database.Execute ("SET NAMES " & Value); Database.Execute ("SET CHARACTER SET " & Value); Database.Execute ("SET CHARACTER_SET_SERVER = '" & Value & "'"); Database.Execute ("SET CHARACTER_SET_DATABASE = '" & Value & "'"); elsif Name /= "user" and Name /= "password" then Database.Execute ("SET " & To_String (Name) & "='" & Value & "'"); end if; end Configure; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Server; Database.Name := Config.Database; -- Configure the connection by setting up the MySQL 'SET X=Y' SQL commands. -- Typical configuration includes: -- encoding=utf8 -- collation_connection=utf8_general_ci Config.Properties.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; end ADO.Drivers.Connections.Mysql;
Use the safe log URI string when a connection error occurs so that the password is not displayed in the log
Use the safe log URI string when a connection error occurs so that the password is not displayed in the log
Ada
apache-2.0
stcarrez/ada-ado
8038f9d44e4bfdf64be15bdcce6a3085f0e05f9d
src/security-controllers-roles.ads
src/security-controllers-roles.ads
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- 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 Security.Contexts; with Security.Permissions; with Util.Beans.Objects; with Util.Serialize.IO.XML; package Security.Controllers.Roles is -- ------------------------------ -- Security Controller -- ------------------------------ -- The <b>Role_Controller</b> implements a simple role based permissions check. -- The permission is granted if the user has the role defined by the controller. type Role_Controller (Count : Positive) is limited new Controller with record Roles : Permissions.Role_Type_Array (1 .. Count); end record; type Role_Controller_Access is access all Role_Controller'Class; -- 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) return Boolean; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last)); Count : Natural := 0; Manager : Security.Permissions.Permission_Manager_Access; end record; -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Security.Permissions.Permission_Manager_Access; package Reader_Config is Config : aliased Controller_Config; end Reader_Config; end Security.Controllers.Roles;
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- 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 Security.Contexts; with Security.Permissions; with Util.Beans.Objects; with Util.Serialize.IO.XML; package Security.Controllers.Roles is -- ------------------------------ -- Security Controller -- ------------------------------ -- The <b>Role_Controller</b> implements a simple role based permissions check. -- The permission is granted if the user has the role defined by the controller. type Role_Controller (Count : Positive) is limited new Controller with record Roles : Permissions.Role_Type_Array (1 .. Count); end record; type Role_Controller_Access is access all Role_Controller'Class; -- 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; type Controller_Config is record Name : Util.Beans.Objects.Object; Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last)); Count : Natural := 0; Manager : Security.Permissions.Permission_Manager_Access; end record; -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Security.Permissions.Permission_Manager_Access; package Reader_Config is Config : aliased Controller_Config; end Reader_Config; end Security.Controllers.Roles;
Add Permission parameter
Add Permission parameter
Ada
apache-2.0
Letractively/ada-security
882842b5615d3be7566cbec8b9f5bcbf055539b2
src/base/beans/util-beans-objects-vectors.ads
src/base/beans/util-beans-objects-vectors.ads
----------------------------------------------------------------------- -- util-beans-vectors -- Object vectors -- Copyright (C) 2011, 2017, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Beans.Basic; -- == Object vectors == -- The `Util.Beans.Objects.Vectors` package provides a vector of objects. -- To create an instance of the vector, it is possible to use the `Create` function -- as follows: -- -- List : Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Create; -- package Util.Beans.Objects.Vectors is package Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Object); subtype Cursor is Vectors.Cursor; subtype Vector is Vectors.Vector; -- Make all the Vectors operations available (a kind of 'use Vectors' for anybody). function Length (Container : in Vector) return Ada.Containers.Count_Type renames Vectors.Length; function Is_Empty (Container : in Vector) return Boolean renames Vectors.Is_Empty; procedure Clear (Container : in out Vector) renames Vectors.Clear; function First (Container : in Vector) return Cursor renames Vectors.First; function Last (Container : in Vector) return Cursor renames Vectors.Last; function Element (Container : in Vector; Position : in Natural) return Object renames Vectors.Element; procedure Append (Container : in out Vector; New_Item : in Object; Count : in Ada.Containers.Count_Type := 1) renames Vectors.Append; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Element : Object)) renames Vectors.Query_Element; procedure Update_Element (Container : in out Vector; Position : in Cursor; Process : not null access procedure (Element : in out Object)) renames Vectors.Update_Element; function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element; function Element (Position : Cursor) return Object renames Vectors.Element; procedure Next (Position : in out Cursor) renames Vectors.Next; function Next (Position : Cursor) return Cursor renames Vectors.Next; function Previous (Position : Cursor) return Cursor renames Vectors.Previous; procedure Previous (Position : in out Cursor) renames Vectors.Previous; -- ------------------------------ -- Vector Bean -- ------------------------------ -- The `Vector_Bean` is a vector of objects that also exposes the <b>Bean</b> interface. -- This allows the vector to be available and accessed from an Object instance. type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean with private; type Vector_Bean_Access is access all Vector_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Vector_Bean; Name : in String) return Object; -- Get the number of elements in the list. overriding function Get_Count (From : in Vector_Bean) return Natural; -- Get the element at the given position. overriding function Get_Row (From : in Vector_Bean; Position : in Natural) return Util.Beans.Objects.Object; -- Create an object that contains a `Vector_Bean` instance. function Create return Object; -- Iterate over the vectors or array elements. -- If the object is not a `Vector_Bean` or an array, the operation does nothing. procedure Iterate (From : in Object; Process : not null access procedure (Item : in Object)); private type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean with null record; end Util.Beans.Objects.Vectors;
----------------------------------------------------------------------- -- util-beans-vectors -- Object vectors -- Copyright (C) 2011, 2017, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Beans.Basic; with Util.Beans.Objects.Iterators; -- == Object vectors == -- The `Util.Beans.Objects.Vectors` package provides a vector of objects. -- To create an instance of the vector, it is possible to use the `Create` function -- as follows: -- -- with Util.Beans.Objects.Vectors; -- ... -- List : Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Create; -- package Util.Beans.Objects.Vectors is subtype Iterator_Bean is Util.Beans.Objects.Iterators.Iterator_Bean; package Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Object); subtype Cursor is Vectors.Cursor; subtype Vector is Vectors.Vector; -- Make all the Vectors operations available (a kind of 'use Vectors' for anybody). function Length (Container : in Vector) return Ada.Containers.Count_Type renames Vectors.Length; function Is_Empty (Container : in Vector) return Boolean renames Vectors.Is_Empty; procedure Clear (Container : in out Vector) renames Vectors.Clear; function First (Container : in Vector) return Cursor renames Vectors.First; function Last (Container : in Vector) return Cursor renames Vectors.Last; function Element (Container : in Vector; Position : in Natural) return Object renames Vectors.Element; procedure Append (Container : in out Vector; New_Item : in Object; Count : in Ada.Containers.Count_Type := 1) renames Vectors.Append; procedure Query_Element (Position : in Cursor; Process : not null access procedure (Element : Object)) renames Vectors.Query_Element; procedure Update_Element (Container : in out Vector; Position : in Cursor; Process : not null access procedure (Element : in out Object)) renames Vectors.Update_Element; function Has_Element (Position : Cursor) return Boolean renames Vectors.Has_Element; function Element (Position : Cursor) return Object renames Vectors.Element; procedure Next (Position : in out Cursor) renames Vectors.Next; function Next (Position : Cursor) return Cursor renames Vectors.Next; function Previous (Position : Cursor) return Cursor renames Vectors.Previous; procedure Previous (Position : in out Cursor) renames Vectors.Previous; -- ------------------------------ -- Vector Bean -- ------------------------------ -- The `Vector_Bean` is a vector of objects that also exposes the <b>Bean</b> interface. -- This allows the vector to be available and accessed from an Object instance. type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean and Iterator_Bean with private; type Vector_Bean_Access is access all Vector_Bean'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Vector_Bean; Name : in String) return Object; -- Get the number of elements in the list. overriding function Get_Count (From : in Vector_Bean) return Natural; -- Get the element at the given position. overriding function Get_Row (From : in Vector_Bean; Position : in Natural) return Util.Beans.Objects.Object; -- Get an iterator to iterate starting with the first element. overriding function First (From : in Vector_Bean) return Iterators.Proxy_Iterator_Access; -- Get an iterator to iterate starting with the last element. overriding function Last (From : in Vector_Bean) return Iterators.Proxy_Iterator_Access; -- Create an object that contains a `Vector_Bean` instance. function Create return Object; -- Iterate over the vectors or array elements. -- If the object is not a `Vector_Bean` or an array, the operation does nothing. procedure Iterate (From : in Object; Process : not null access procedure (Position : in Positive; Item : in Object)); private type Vector_Bean is new Vectors.Vector and Util.Beans.Basic.Array_Bean and Iterator_Bean with null record; type Vector_Iterator is new Iterators.Proxy_Iterator with record Pos : Cursor; end record; type Vector_Iterator_Access is access all Vector_Iterator; overriding function Has_Element (Iter : in Vector_Iterator) return Boolean; overriding procedure Next (Iter : in out Vector_Iterator); overriding procedure Previous (Iter : in out Vector_Iterator); overriding function Element (Iter : in Vector_Iterator) return Object; end Util.Beans.Objects.Vectors;
Implement the Iterator_Bean to allow iterating over the vector
Implement the Iterator_Bean to allow iterating over the vector
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
af705926ea576b3513554d9e73f20860da2f066e
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, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Properties; with Util.Beans.Objects; 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"); type Wallet_Manager is limited new Util.Properties.Implementation.Manager with record Wallet : Keystore.Properties.Manager; Props : ASF.Applications.Config; Length : Positive; Prefix : String (1 .. MAX_PREFIX_LENGTH); end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Wallet_Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Wallet_Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Wallet_Manager; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Wallet_Manager; Name : in String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Wallet_Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Wallet_Manager) return Util.Properties.Implementation.Manager_Access; package Shared_Manager is new Util.Properties.Implementation.Shared_Implementation (Wallet_Manager); subtype Property_Map is Shared_Manager.Manager; type Property_Map_Access is access all Property_Map; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Wallet_Manager; Name : in String) return Util.Beans.Objects.Object is Prefixed_Name : constant String := From.Prefix (1 .. From.Length) & Name; begin if From.Wallet.Exists (Prefixed_Name) then declare Value : constant String := From.Wallet.Get (Prefixed_Name); begin return Util.Beans.Objects.To_Object (Value); end; else return From.Props.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ overriding procedure Set_Value (From : in out Wallet_Manager; Name : in String; Value : in Util.Beans.Objects.Object) is Prefixed_Name : constant String := From.Prefix (1 .. From.Length) & Name; begin if From.Wallet.Exists (Prefixed_Name) then From.Wallet.Set_Value (Prefixed_Name, Value); else From.Props.Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Wallet_Manager; Name : in String) return Boolean is begin return Self.Props.Exists (Name) or else Self.Wallet.Exists (Self.Prefix (1 .. Self.Length) & Name); end Exists; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Wallet_Manager; Name : in String) is Prefixed_Name : constant String := Self.Prefix (1 .. Self.Length) & Name; begin if Self.Wallet.Exists (Prefixed_Name) then Self.Wallet.Remove (Prefixed_Name); else Self.Props.Remove (Name); end if; end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Wallet_Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is begin Self.Props.Iterate (Process); end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Wallet_Manager) return Util.Properties.Implementation.Manager_Access is Result : constant Property_Map_Access := new Property_Map; begin Result.Length := Self.Length; Result.Wallet := Self.Wallet; Result.Props := Self.Props; Result.Prefix := Self.Prefix; return Result.all'Access; end Create_Copy; -- ------------------------------ -- Merge the configuration content and the keystore to a final configuration object. -- The keystore can be used to store sensitive information such as database connection, -- secret keys while the rest of the configuration remains in clear property files. -- The keystore must be unlocked to have access to its content. -- The prefix parameter is used to prefix names from the keystore so that the same -- keystore could be used by several applications. -- ------------------------------ procedure Merge (Into : in out ASF.Applications.Config; Config : in out ASF.Applications.Config; Wallet : in out Keystore.Properties.Manager; Prefix : in String) is function Allocate return Util.Properties.Implementation.Shared_Manager_Access; function Allocate return Util.Properties.Implementation.Shared_Manager_Access is Result : constant Property_Map_Access := new Property_Map; begin Result.Length := Prefix'Length; Result.Wallet := Wallet; Result.Props := Config; Result.Prefix (1 .. Result.Length) := Prefix; return Result.all'Access; end Allocate; procedure Setup is new Util.Properties.Implementation.Initialize (Allocate); begin Setup (Into); end Merge; -- ------------------------------ -- 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;
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012, 2015, 2017, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Ada.Directories; with Ada.Strings.Unbounded; with Util.Strings; with Util.Properties; with Util.Beans.Objects; 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"); type Wallet_Manager is limited new Util.Properties.Implementation.Manager with record Wallet : Keystore.Properties.Manager; Props : ASF.Applications.Config; Length : Positive; Prefix : String (1 .. MAX_PREFIX_LENGTH); end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Wallet_Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Wallet_Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. overriding function Exists (Self : in Wallet_Manager; Name : in String) return Boolean; -- Remove the property given its name. overriding procedure Remove (Self : in out Wallet_Manager; Name : in String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. overriding procedure Iterate (Self : in Wallet_Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)); -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Wallet_Manager) return Util.Properties.Implementation.Manager_Access; package Shared_Manager is new Util.Properties.Implementation.Shared_Implementation (Wallet_Manager); subtype Property_Map is Shared_Manager.Manager; type Property_Map_Access is access all Property_Map; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Wallet_Manager; Name : in String) return Util.Beans.Objects.Object is Prefixed_Name : constant String := From.Prefix (1 .. From.Length) & Name; begin if From.Wallet.Exists (Prefixed_Name) then declare Value : constant String := From.Wallet.Get (Prefixed_Name); begin return Util.Beans.Objects.To_Object (Value); end; else return From.Props.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. -- ------------------------------ overriding procedure Set_Value (From : in out Wallet_Manager; Name : in String; Value : in Util.Beans.Objects.Object) is Prefixed_Name : constant String := From.Prefix (1 .. From.Length) & Name; begin if From.Wallet.Exists (Prefixed_Name) then From.Wallet.Set_Value (Prefixed_Name, Value); else From.Props.Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Returns TRUE if the property exists. -- ------------------------------ function Exists (Self : in Wallet_Manager; Name : in String) return Boolean is begin return Self.Props.Exists (Name) or else Self.Wallet.Exists (Self.Prefix (1 .. Self.Length) & Name); end Exists; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Wallet_Manager; Name : in String) is Prefixed_Name : constant String := Self.Prefix (1 .. Self.Length) & Name; begin if Self.Wallet.Exists (Prefixed_Name) then Self.Wallet.Remove (Prefixed_Name); else Self.Props.Remove (Name); end if; end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Wallet_Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is procedure Wallet_Filter (Name : in String; Item : in Util.Beans.Objects.Object); procedure Property_Filter (Name : in String; Item : in Util.Beans.Objects.Object); procedure Wallet_Filter (Name : in String; Item : in Util.Beans.Objects.Object) is begin if Util.Strings.Starts_With (Name, Self.Prefix (1 .. Self.Length)) then Process (Name (Name'First + Self.Length .. Name'Last), Item); end if; end Wallet_Filter; procedure Property_Filter (Name : in String; Item : in Util.Beans.Objects.Object) is Prefixed_Name : constant String := Self.Prefix (1 .. Self.Length) & Name; begin if not Self.Wallet.Exists (Prefixed_Name) then Process (Name, Item); end if; end Property_Filter; begin Self.Props.Iterate (Property_Filter'Access); Self.Wallet.Iterate (Wallet_Filter'Access); end Iterate; -- ------------------------------ -- Deep copy of properties stored in 'From' to 'To'. -- ------------------------------ function Create_Copy (Self : in Wallet_Manager) return Util.Properties.Implementation.Manager_Access is Result : constant Property_Map_Access := new Property_Map; begin Result.Length := Self.Length; Result.Wallet := Self.Wallet; Result.Props := Self.Props; Result.Prefix := Self.Prefix; return Result.all'Access; end Create_Copy; -- ------------------------------ -- Merge the configuration content and the keystore to a final configuration object. -- The keystore can be used to store sensitive information such as database connection, -- secret keys while the rest of the configuration remains in clear property files. -- The keystore must be unlocked to have access to its content. -- The prefix parameter is used to prefix names from the keystore so that the same -- keystore could be used by several applications. -- ------------------------------ procedure Merge (Into : in out ASF.Applications.Config; Config : in out ASF.Applications.Config; Wallet : in out Keystore.Properties.Manager; Prefix : in String) is function Allocate return Util.Properties.Implementation.Shared_Manager_Access; function Allocate return Util.Properties.Implementation.Shared_Manager_Access is Result : constant Property_Map_Access := new Property_Map; begin Result.Length := Prefix'Length; Result.Wallet := Wallet; Result.Props := Config; Result.Prefix (1 .. Result.Length) := Prefix; return Result.all'Access; end Allocate; procedure Setup is new Util.Properties.Implementation.Initialize (Allocate); begin Setup (Into); end Merge; -- ------------------------------ -- 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;
Fix the Iterate procedure to iterate over the configuration properties and filter them based on the wallet prefix
Fix the Iterate procedure to iterate over the configuration properties and filter them based on the wallet prefix
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
bf8b0215f169e9295f130d5d0bb99b383374328c
awa/src/awa-permissions-services.adb
awa/src/awa-permissions-services.adb
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- 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.Queries; with ADO.Sessions.Entities; with ADO.Statements; with Util.Log.Loggers; with Util.Serialize.IO.XML; with Security.Controllers.Roles; with AWA.Permissions.Models; with AWA.Services.Contexts; package body AWA.Permissions.Services is use Util.Log; use ADO.Sessions; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions.Services"); -- ------------------------------ -- Get the permission manager associated with the security context. -- Returns null if there is none. -- ------------------------------ function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access is use type Security.Permissions.Permission_Manager_Access; M : constant Security.Permissions.Permission_Manager_Access := Context.Get_Permission_Manager; begin if M = null then Log.Info ("There is no permission manager"); return null; elsif not (M.all in Permission_Manager'Class) then Log.Info ("Permission manager is not a AWA permission manager"); return null; else return Permission_Manager'Class (M.all)'Access; end if; end Get_Permission_Manager; -- ------------------------------ -- Get the application instance. -- ------------------------------ function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access is begin return Manager.App; end Get_Application; -- ------------------------------ -- Set the application instance. -- ------------------------------ procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access) is begin Manager.App := App; end Set_Application; -- ------------------------------ -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Perm : AWA.Permissions.Models.ACL_Ref; begin Log.Info ("Adding permission"); Ctx.Start; Perm.Set_Entity_Type (Kind); Perm.Set_User_Id (Ctx.Get_User_Identifier); Perm.Set_Entity_Id (Entity); Perm.Set_Writeable (Permission = AWA.Permissions.WRITE); Perm.Save (DB); Ctx.Commit; end Add_Permission; -- ------------------------------ -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. -- ------------------------------ procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager, Permission); use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission); Query.Bind_Param ("user_id", User); Query.Bind_Param ("entity_id", Entity); Query.Bind_Param ("entity_type", Integer (Kind)); declare Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query); begin Stmt.Execute; if not Stmt.Has_Elements then Log.Info ("User {0} does not have permission to access entity {1}/{2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); raise NO_PERMISSION; end if; end; end Check_Permission; -- ------------------------------ -- Read the policy file -- ------------------------------ overriding procedure Read_Policy (Manager : in out Permission_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Security.Permissions.Reader_Config (Reader, Manager'Unchecked_Access); package Role_Config is new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); -- package Entity_Config is -- new AWA.Permissions.Controllers.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); pragma Warnings (Off, Role_Config); -- pragma Warnings (Off, Entity_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Parse (File); end Read_Policy; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type := READ) is Acl : AWA.Permissions.Models.ACL_Ref; begin Acl.Set_User_Id (User); Acl.Set_Entity_Type (Kind); Acl.Set_Entity_Id (Entity); Acl.Set_Writeable (Permission = WRITE); Acl.Save (Session); Log.Info ("Permission created for {0} to access {1}, entity type {2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); end Add_Permission; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Permission : in Permission_Type := READ) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session => Session, Object => Key); begin Add_Permission (Session, User, ADO.Objects.Get_Value (Key), Kind, Permission); end Add_Permission; -- ------------------------------ -- Create a permission manager for the given application. -- ------------------------------ function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Permissions.Permission_Manager_Access is Result : constant AWA.Permissions.Services.Permission_Manager_Access := new AWA.Permissions.Services.Permission_Manager; begin Result.Set_Application (App); return Result.all'Access; end Create_Permission_Manager; end AWA.Permissions.Services;
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions.Entities; with ADO.Statements; with Util.Log.Loggers; with Util.Serialize.IO.XML; with AWA.Permissions.Models; with AWA.Services.Contexts; package body AWA.Permissions.Services is use Util.Log; use ADO.Sessions; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions.Services"); -- ------------------------------ -- Get the permission manager associated with the security context. -- Returns null if there is none. -- ------------------------------ function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access is use type Security.Policies.Policy_Manager_Access; M : constant Security.Policies.Policy_Manager_Access := Context.Get_Permission_Manager; begin if M = null then Log.Info ("There is no permission manager"); return null; elsif not (M.all in Permission_Manager'Class) then Log.Info ("Permission manager is not a AWA permission manager"); return null; else return Permission_Manager'Class (M.all)'Access; end if; end Get_Permission_Manager; -- ------------------------------ -- Get the application instance. -- ------------------------------ function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access is begin return Manager.App; end Get_Application; -- ------------------------------ -- Set the application instance. -- ------------------------------ procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access) is begin Manager.App := App; end Set_Application; -- ------------------------------ -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager); Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Perm : AWA.Permissions.Models.ACL_Ref; begin Log.Info ("Adding permission"); Ctx.Start; Perm.Set_Entity_Type (Kind); Perm.Set_User_Id (Ctx.Get_User_Identifier); Perm.Set_Entity_Id (Entity); Perm.Set_Writeable (Permission = AWA.Permissions.WRITE); Perm.Save (DB); Ctx.Commit; end Add_Permission; -- ------------------------------ -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. -- ------------------------------ procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type) is pragma Unreferenced (Manager, Permission); use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : constant Session := AWA.Services.Contexts.Get_Session (Ctx); Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Permissions.Models.Query_Check_Entity_Permission); Query.Bind_Param ("user_id", User); Query.Bind_Param ("entity_id", Entity); Query.Bind_Param ("entity_type", Integer (Kind)); declare Stmt : ADO.Statements.Query_Statement := DB.Create_Statement (Query); begin Stmt.Execute; if not Stmt.Has_Elements then Log.Info ("User {0} does not have permission to access entity {1}/{2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); raise NO_PERMISSION; end if; end; end Check_Permission; -- ------------------------------ -- Read the policy file -- ------------------------------ overriding procedure Read_Policy (Manager : in out Permission_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; -- package Policy_Config is -- new Security.Permissions.Reader_Config (Reader, Manager'Unchecked_Access); -- package Role_Config is -- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); -- pragma Warnings (Off, Policy_Config); -- pragma Warnings (Off, Role_Config); -- pragma Warnings (Off, Entity_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Parse (File); end Read_Policy; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type := READ) is Acl : AWA.Permissions.Models.ACL_Ref; begin Acl.Set_User_Id (User); Acl.Set_Entity_Type (Kind); Acl.Set_Entity_Id (Entity); Acl.Set_Writeable (Permission = WRITE); Acl.Save (Session); Log.Info ("Permission created for {0} to access {1}, entity type {2}", ADO.Identifier'Image (User), ADO.Identifier'Image (Entity), ADO.Entity_Type'Image (Kind)); end Add_Permission; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Permission : in Permission_Type := READ) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; Kind : constant ADO.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session => Session, Object => Key); begin Add_Permission (Session, User, ADO.Objects.Get_Value (Key), Kind, Permission); end Add_Permission; -- ------------------------------ -- Create a permission manager for the given application. -- ------------------------------ function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access is Result : constant AWA.Permissions.Services.Permission_Manager_Access := new AWA.Permissions.Services.Permission_Manager (10); begin Result.Set_Application (App); return Result.all'Access; end Create_Permission_Manager; end AWA.Permissions.Services;
Fix compilation after refactoring Security package
Fix compilation after refactoring Security package
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
cd213fd783f00a1404a8f5640b169f7d6b436431
awa/src/awa-permissions-beans.adb
awa/src/awa-permissions-beans.adb
----------------------------------------------------------------------- -- awa-permissions-beans -- Permission beans -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Events.Action_Method; with AWA.Permissions.Services; package body AWA.Permissions.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; package Create_Binding is new AWA.Events.Action_Method.Bind (Bean => Permission_Bean, Method => Create, Name => "create"); Permission_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Binding.Proxy'Access); -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Permission_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_id" then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_type" then From.Kind := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "workspace_id" then From.Set_Workspace_Id (ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Permission_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Permission_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new permission. -- ------------------------------ procedure Create (Bean : in out Permission_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; begin Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, To_String (Bean.Kind)); -- AWA.Permissions.Services.Add_Permission (Session => DB, -- Entity => Bean.Get_Entity_Id, -- Kind => Kind, -- User => Ctx.Get_User_Identifier, -- Workspace => Bean.Get_Workspace_Id); Ctx.Commit; end Create; -- ------------------------------ -- Create the permission bean instance. -- ------------------------------ function Create_Permission_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Permission_Bean; end Create_Permission_Bean; end AWA.Permissions.Beans;
----------------------------------------------------------------------- -- awa-permissions-beans -- Permission beans -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with ADO.Utils; with ADO.Sessions; with ADO.Sessions.Entities; with AWA.Services.Contexts; with AWA.Events.Action_Method; with AWA.Permissions.Services; package body AWA.Permissions.Beans is use Ada.Strings.Unbounded; package ASC renames AWA.Services.Contexts; package Create_Binding is new AWA.Events.Action_Method.Bind (Bean => Permission_Bean, Method => Create, Name => "create"); Permission_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Binding.Proxy'Access); -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Permission_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_id" then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_type" then From.Kind := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "workspace_id" then From.Set_Workspace_Id (ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Permission_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Permission_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a new permission. -- ------------------------------ procedure Create (Bean : in out Permission_Bean; Event : in AWA.Events.Module_Event'Class) is pragma Unreferenced (Event); Ctx : constant ASC.Service_Context_Access := ASC.Current; Manager : constant Services.Permission_Manager_Access := Services.Get_Permission_Manager (Ctx); List : constant Security.Permissions.Permission_Index_Array := Security.Permissions.Get_Permission_Array (To_String (Bean.Permission)); DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Kind : ADO.Entity_Type; begin Ctx.Start; Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, To_String (Bean.Kind)); for Perm of List loop Manager.Add_Permission (Session => DB, User => Ctx.Get_User_Identifier, Entity => Bean.Get_Entity_Id, Kind => Kind, Workspace => Bean.Get_Workspace_Id, Permission => Perm); end loop; Ctx.Commit; end Create; -- ------------------------------ -- Create the permission bean instance. -- ------------------------------ function Create_Permission_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Permission_Bean; end Create_Permission_Bean; end AWA.Permissions.Beans;
Fix the permission bean to get a list of permission and add them
Fix the permission bean to get a list of permission and add them
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7e92448330d76eecf79ef904f3cb69180624da43
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; with Security.Permissions; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); 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"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; 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); -- 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 type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Events; with AWA.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; 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"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class; 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); -- 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 type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
Define the Create_Page_Event and Create_Content_Event event definitions
Define the Create_Page_Event and Create_Content_Event event definitions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f7c0f99a7bff22ee07af82012918657895495f39
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
Implement new function Get_Policy Keep the policy index in the policy instance
Implement new function Get_Policy Keep the policy index in the policy instance
Ada
apache-2.0
Letractively/ada-security
1693e5afb2539dad26fd11a4ba70f3c4df2ce8e4
src/gen-commands-layout.adb
src/gen-commands-layout.adb
----------------------------------------------------------------------- -- gen-commands-layout -- Layout creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with Util.Strings; with Util.Files; package body Gen.Commands.Layout is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Strings.Unbounded; function Get_Layout return String; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory; Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts"); function Get_Name return String is Name : constant String := Get_Argument; Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is Layout : constant String := Get_Argument; begin if Layout'Length = 0 then return "layout"; end if; if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout); return "layout"; end Get_Layout; Name : constant String := Get_Name; Layout : constant String := Get_Layout; begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Layout_Dir); Generator.Set_Global ("pageName", Name); Generator.Set_Global ("layout", Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("add-layout: Add a new layout page to the application"); Put_Line ("Usage: add-layout NAME [FORM]"); New_Line; Put_Line (" The layout page allows to give a common look to a set of pages."); Put_Line (" You can create several layouts for your application."); Put_Line (" Each layout can reference one or several building blocks that are defined"); Put_Line (" in the original page."); New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/WEB-INF/layouts/<name>.xhtml"); end Help; end Gen.Commands.Layout;
----------------------------------------------------------------------- -- gen-commands-layout -- Layout creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with Util.Strings; with Util.Files; package body Gen.Commands.Layout is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Strings.Unbounded; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory; Layout_Dir : constant String := Util.Files.Compose (Dir, "web/WEB-INF/layouts"); function Get_Name return String is Name : constant String := Get_Argument; Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; Name : constant String := Get_Name; begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Layout_Dir); Generator.Set_Global ("pageName", Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "layout"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("add-layout: Add a new layout page to the application"); Put_Line ("Usage: add-layout NAME"); New_Line; Put_Line (" The layout page allows to give a common look to a set of pages."); Put_Line (" You can create several layouts for your application."); Put_Line (" Each layout can reference one or several building blocks that are defined"); Put_Line (" in the original page."); New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/WEB-INF/layouts/<name>.xhtml"); end Help; end Gen.Commands.Layout;
Fix and cleanup the layout command
Fix and cleanup the layout command
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
ebaf59ef50aebc0b5c1246aa299b7c2e5eb345b6
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is use Ada.Strings.Wide_Wide_Unbounded; -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; Tag : Wiki.Html_Tag; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Tag := Wiki.Find_Tag (To_Wide_Wide_String (Name)); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Tag); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Tag, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Ada.Characters.Conversions.To_Character (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Ada.Characters.Conversions.To_Wide_Wide_Character (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is use Ada.Strings.Wide_Wide_Unbounded; -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wide_Wide_Character) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String); function Is_Letter (C : in Wide_Wide_Character) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; begin Name := To_Unbounded_Wide_Wide_String (""); Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Ada.Strings.Wide_Wide_Unbounded.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Unbounded_Wide_Wide_String) is C : Wide_Wide_Character; Token : Wide_Wide_Character; begin Value := To_Unbounded_Wide_Wide_String (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is C : Wide_Wide_Character; Name : Unbounded_Wide_Wide_String; Value : Unbounded_Wide_Wide_String; begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Attributes.Append (P.Attributes, Name, Value); elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end loop; -- Peek (P, C); -- Add any pending attribute. if Length (Name) > 0 then Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wide_Wide_Character; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wide_Wide_Character; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is Name : Unbounded_Wide_Wide_String; C : Wide_Wide_Character; Tag : Wiki.Html_Tag; begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Tag := Wiki.Find_Tag (To_Wide_Wide_String (Name)); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); End_Element (P, Tag); else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; Start_Element (P, Tag, P.Attributes); end if; end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wide_Wide_Character) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wide_Wide_Character; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
Use the Wiki.Strings.To_Char and Wiki.Strings.To_WChar functions
Use the Wiki.Strings.To_Char and Wiki.Strings.To_WChar functions
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
9856ee729d71cd6c5550c62f373d631fa855f729
src/wiki-streams-html.adb
src/wiki-streams-html.adb
----------------------------------------------------------------------- -- wiki-streams-html -- Wiki HTML output stream -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Streams.Html is -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ procedure Write_Attribute (Writer : in out Html_Output_Stream'Class; Name : in String; Content : in String) is begin Writer.Write_Attribute (Name, Ada.Characters.Conversions.To_Wide_Wide_String (Content)); end Write_Attribute; end Wiki.Streams.Html;
----------------------------------------------------------------------- -- wiki-streams-html -- Wiki HTML output stream -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; package body Wiki.Streams.Html is -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ procedure Write_Attribute (Writer : in out Html_Output_Stream'Class; Name : in String; Content : in String) is begin Writer.Write_Wide_Attribute (Name, Ada.Characters.Conversions.To_Wide_Wide_String (Content)); end Write_Attribute; end Wiki.Streams.Html;
Fix Write_Attribute implementation
Fix Write_Attribute implementation
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
db61001b1d522925e783db2a4c9315ab4f74e109
src/wiki-filters.adb
src/wiki-filters.adb
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Document.Append (Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Documents.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Documents.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Document.Push_Node (Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Document.Pop_Node (Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Document.Add_Blockquote (Level); end if; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List_Item (Document, Level, Ordered); else Document.Add_List_Item (Level, Ordered); end if; end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Document.Add_Link (Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Document.Add_Image (Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Document.Add_Quote (Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Document.Add_Preformatted (Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; -- ------------------------------ -- Add the filter at beginning of the filter chain. -- ------------------------------ procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access) is begin Filter.Next := Chain.Next; Chain.Next := Filter; end Add_Filter; -- ------------------------------ -- Internal operation to copy the filter chain. -- ------------------------------ procedure Set_Chain (Chain : in out Filter_Chain; From : in Filter_Chain'Class) is begin Chain.Next := From.Next; end Set_Chain; end Wiki.Filters;
----------------------------------------------------------------------- -- wiki-filters -- Wiki filters -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Filters is -- ------------------------------ -- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document. -- ------------------------------ procedure Add_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Kind : in Wiki.Nodes.Simple_Node_Kind) is begin if Filter.Next /= null then Filter.Next.Add_Node (Document, Kind); else Document.Append (Kind); end if; end Add_Node; -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ procedure Add_Text (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin if Filter.Next /= null then Filter.Next.Add_Text (Document, Text, Format); else Wiki.Documents.Append (Document, Text, Format); end if; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ procedure Add_Header (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Header (Document, Header, Level); else Wiki.Documents.Append (Document, Header, Level); end if; end Add_Header; -- ------------------------------ -- Push a HTML node with the given tag to the document. -- ------------------------------ procedure Push_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Push_Node (Document, Tag, Attributes); else Document.Push_Node (Tag, Attributes); end if; end Push_Node; -- ------------------------------ -- Pop a HTML node with the given tag. -- ------------------------------ procedure Pop_Node (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Tag : in Wiki.Html_Tag) is begin if Filter.Next /= null then Filter.Next.Pop_Node (Document, Tag); else Document.Pop_Node (Tag); end if; end Pop_Node; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Natural) is begin if Filter.Next /= null then Filter.Next.Add_Blockquote (Document, Level); else Document.Add_Blockquote (Level); end if; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Level : in Positive; Ordered : in Boolean) is begin if Filter.Next /= null then Filter.Next.Add_List_Item (Document, Level, Ordered); else Document.Add_List_Item (Level, Ordered); end if; end Add_List_Item; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Link (Document, Name, Attributes); else Document.Add_Link (Name, Attributes); end if; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Image (Document, Name, Attributes); else Document.Add_Image (Name, Attributes); end if; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Quote (Document, Name, Attributes); else Document.Add_Quote (Name, Attributes); end if; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin if Filter.Next /= null then Filter.Next.Add_Preformatted (Document, Text, Format); else Document.Add_Preformatted (Text, Format); end if; end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Add_Row (Document); else Document.Add_Row; end if; end Add_Row; -- ------------------------------ -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. -- ------------------------------ procedure Add_Column (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document; Attributes : in out Wiki.Attributes.Attribute_List) is begin if Filter.Next /= null then Filter.Next.Add_Column (Document, Attributes); else Document.Add_Column (Attributes); end if; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish_Table (Document); else Document.Finish_Table; end if; end Finish_Table; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ procedure Finish (Filter : in out Filter_Type; Document : in out Wiki.Documents.Document) is begin if Filter.Next /= null then Filter.Next.Finish (Document); end if; end Finish; -- ------------------------------ -- Add the filter at beginning of the filter chain. -- ------------------------------ procedure Add_Filter (Chain : in out Filter_Chain; Filter : in Filter_Type_Access) is begin Filter.Next := Chain.Next; Chain.Next := Filter; end Add_Filter; -- ------------------------------ -- Internal operation to copy the filter chain. -- ------------------------------ procedure Set_Chain (Chain : in out Filter_Chain; From : in Filter_Chain'Class) is begin Chain.Next := From.Next; end Set_Chain; end Wiki.Filters;
Add support for wiki tables - implement Add_Row, Add_Column and Finish_Table
Add support for wiki tables - implement Add_Row, Add_Column and Finish_Table
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
bd843fae345b2742fc159046f719b191dc9e0691
src/wiki-helpers.ads
src/wiki-helpers.ads
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki.Helpers is pragma Preelaborate; LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wide_Wide_Character) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wide_Wide_String) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wide_Wide_String) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Strings; package Wiki.Helpers is pragma Preelaborate; LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#); CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#); HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wiki.Strings.WString) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean; -- Given the current tag on the top of the stack and the new tag that will be pushed, -- decide whether the current tag must be closed or not. -- Returns True if the current tag must be closed. function Need_Close (Tag : in Html_Tag; Current_Tag : in Html_Tag) return Boolean; end Wiki.Helpers;
Use the Wiki.Strings.WChar type
Use the Wiki.Strings.WChar type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
53ef4ca825967a8475450dd16986b9f3cc2874ca
matp/regtests/mat-frames-tests.adb
matp/regtests/mat-frames-tests.adb
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- 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 Ada.Directories; with Util.Test_Caller; with MAT.Frames.Print; with MAT.Readers.Streams.Files; package body MAT.Frames.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); -- Builtin and well known definition of test frames. Frame_1_0 : constant Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); Frame_1_1 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_15); Frame_1_2 : constant Frame_Table (1 .. 16) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_20, 1_21); Frame_1_3 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_30); Frame_2_0 : constant Frame_Table (1 .. 10) := (2_0, 2_2, 2_3, 2_4, 2_5, 2_6, 2_7, 2_8, 2_9, 2_10); Frame_2_1 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_10); Frame_2_2 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1); Frame_2_3 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_3, 2_1, 2_1, 2_1, 2_1); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Frames.Insert", Test_Simple_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Find", Test_Find_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Backtrace", Test_Complex_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Release", Test_Release_Frames'Access); end Add_Tests; -- ------------------------------ -- Create a tree with the well known test frames. -- ------------------------------ function Create_Test_Frames return Frame_Type is Root : Frame_Type := Create_Root; F : Frame_Type; begin Insert (Root, Frame_1_0, F); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); return Root; end Create_Test_Frames; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Simple_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F : Frame_Type; begin -- Consistency check on empty tree. Util.Tests.Assert_Equals (T, 0, Count_Children (Root), "Empty frame: Count_Children must return 0"); Util.Tests.Assert_Equals (T, 0, Current_Depth (Root), "Empty frame: Current_Depth must return 0"); -- Insert first frame and verify consistency. Insert (Root, Frame_1_0, F); Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); -- Expect (Msg => "Frames.Count_Children", -- Val => 1, -- Result => Count_Children (Root)); -- Expect (Msg => "Frames.Count_Children(recursive)", -- Val => 1, -- Result => Count_Children (Root, True)); -- Expect (Msg => "Frames.Current_Depth", -- Val => 10, -- Result => Current_Depth (F)); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 3, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 3"); Util.Tests.Assert_Equals (T, 15, Current_Depth (F), "Simple frame: Current_Depth must return 15"); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 2, Count_Children (Root), "Simple frame: Count_Children must return 2"); Util.Tests.Assert_Equals (T, 7, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 7"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); Destroy (Root); end Test_Simple_Frames; -- ------------------------------ -- Test searching in the frame. -- ------------------------------ procedure Test_Find_Frames (T : in out Test) is Root : Frame_Type := Create_Test_Frames; Result : Frame_Type; Last_Pc : Natural; begin -- Find exact frame. Find (Root, Frame_2_3, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); T.Assert (Last_Pc = 0, "Frames.Find must return a 0 Last_Pc"); declare Pc : Frame_Table (1 .. 8) := Frame_2_3 (1 .. 8); begin Find (Root, Pc, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); -- Expect (Msg => "Frames.Find (Last_Pc param)", -- Val => 0, -- Result => Last_Pc); end; Destroy (Root); end Test_Find_Frames; -- ------------------------------ -- Create a complex frame tree and run tests on it. -- ------------------------------ procedure Test_Complex_Frames (T : in out Test) is Pc : Frame_Table (1 .. 8); Root : Frame_Type := Create_Root; procedure Create_Frame (Depth : in Natural); procedure Create_Frame (Depth : in Natural) is use type MAT.Types.Target_Addr; use type MAT.Events.Frame_Table; F : Frame_Type; begin Pc (Depth) := MAT.Types.Target_Addr (Depth); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; Insert (Root, Pc (1 .. Depth), F); Pc (Depth) := MAT.Types.Target_Addr (Depth) + 1000; Insert (Root, Pc (1 .. Depth), F); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; declare Read_Pc : Frame_Table := Backtrace (F); begin T.Assert (Read_Pc = Pc (1 .. Depth), "Frames.backtrace (same as inserted)"); if Verbose then for I in Read_Pc'Range loop Ada.Text_IO.Put (" " & MAT.Types.Target_Addr'Image (Read_Pc (I))); end loop; Ada.Text_IO.New_Line; end if; end; end Create_Frame; begin Create_Frame (1); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Destroy (Root); end Test_Complex_Frames; -- ------------------------------ -- Test allocating and releasing frames. -- ------------------------------ procedure Test_Release_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F1 : Frame_Type; F2 : Frame_Type; F3 : Frame_Type; begin Insert (Root, Frame_1_1, F1); T.Assert (Root.Used > 0, "Insert must increment the root used count"); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_2, F2); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_3, F3); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Output, "Release frame F1"); Release (F1); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); T.Assert (F2.Used > 0, "Release must not change other frames"); T.Assert (Root.Used > 0, "Release must not change root frame"); Destroy (Root); end Test_Release_Frames; end MAT.Frames.Tests;
----------------------------------------------------------------------- -- mat-readers-tests -- Unit tests for MAT readers -- 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.Text_IO; with Ada.Directories; with Util.Test_Caller; with MAT.Events; with MAT.Frames.Print; with MAT.Readers.Streams.Files; package body MAT.Frames.Tests is use Util.Tests; package Caller is new Util.Test_Caller (Test, "Files"); -- Builtin and well known definition of test frames. Frame_1_0 : constant Frame_Table (1 .. 10) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10); Frame_1_1 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_15); Frame_1_2 : constant Frame_Table (1 .. 16) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_20, 1_21); Frame_1_3 : constant Frame_Table (1 .. 15) := (1_0, 1_2, 1_3, 1_4, 1_5, 1_6, 1_7, 1_8, 1_9, 1_10, 1_11, 1_12, 1_13, 1_14, 1_30); Frame_2_0 : constant Frame_Table (1 .. 10) := (2_0, 2_2, 2_3, 2_4, 2_5, 2_6, 2_7, 2_8, 2_9, 2_10); Frame_2_1 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_10); Frame_2_2 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1, 2_1); Frame_2_3 : constant Frame_Table (1 .. 10) := (2_0, 2_1, 2_2, 2_1, 2_1, 2_3, 2_1, 2_1, 2_1, 2_1); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test MAT.Frames.Insert", Test_Simple_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Find", Test_Find_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Backtrace", Test_Complex_Frames'Access); Caller.Add_Test (Suite, "Test MAT.Frames.Release", Test_Release_Frames'Access); end Add_Tests; -- ------------------------------ -- Create a tree with the well known test frames. -- ------------------------------ function Create_Test_Frames return Frame_Type is Root : Frame_Type := Create_Root; F : Frame_Type; begin Insert (Root, Frame_1_0, F); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); return Root; end Create_Test_Frames; -- ------------------------------ -- Basic consistency checks when creating the test tree -- ------------------------------ procedure Test_Simple_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F : Frame_Type; begin -- Consistency check on empty tree. Util.Tests.Assert_Equals (T, 0, Count_Children (Root), "Empty frame: Count_Children must return 0"); Util.Tests.Assert_Equals (T, 0, Current_Depth (Root), "Empty frame: Current_Depth must return 0"); -- Insert first frame and verify consistency. Insert (Root, Frame_1_0, F); Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); -- Expect (Msg => "Frames.Count_Children", -- Val => 1, -- Result => Count_Children (Root)); -- Expect (Msg => "Frames.Count_Children(recursive)", -- Val => 1, -- Result => Count_Children (Root, True)); -- Expect (Msg => "Frames.Current_Depth", -- Val => 10, -- Result => Current_Depth (F)); Insert (Root, Frame_1_1, F); Insert (Root, Frame_1_2, F); Insert (Root, Frame_1_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 1, Count_Children (Root), "Simple frame: Count_Children must return 1"); Util.Tests.Assert_Equals (T, 3, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 3"); Util.Tests.Assert_Equals (T, 15, Current_Depth (F), "Simple frame: Current_Depth must return 15"); Insert (Root, Frame_2_0, F); Insert (Root, Frame_2_1, F); Insert (Root, Frame_2_2, F); Insert (Root, Frame_2_3, F); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Util.Tests.Assert_Equals (T, 2, Count_Children (Root), "Simple frame: Count_Children must return 2"); Util.Tests.Assert_Equals (T, 7, Count_Children (Root, True), "Simple frame: Count_Children (recursive) must return 7"); Util.Tests.Assert_Equals (T, 10, Current_Depth (F), "Simple frame: Current_Depth must return 10"); Destroy (Root); end Test_Simple_Frames; -- ------------------------------ -- Test searching in the frame. -- ------------------------------ procedure Test_Find_Frames (T : in out Test) is Root : Frame_Type := Create_Test_Frames; Result : Frame_Type; Last_Pc : Natural; begin -- Find exact frame. Find (Root, Frame_2_3, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); T.Assert (Last_Pc = 0, "Frames.Find must return a 0 Last_Pc"); declare Pc : Frame_Table (1 .. 8) := Frame_2_3 (1 .. 8); begin Find (Root, Pc, Result, Last_Pc); T.Assert (Result /= Root, "Frames.Find must return a valid frame"); -- Expect (Msg => "Frames.Find (Last_Pc param)", -- Val => 0, -- Result => Last_Pc); end; Destroy (Root); end Test_Find_Frames; -- ------------------------------ -- Create a complex frame tree and run tests on it. -- ------------------------------ procedure Test_Complex_Frames (T : in out Test) is Pc : Frame_Table (1 .. 8); Root : Frame_Type := Create_Root; procedure Create_Frame (Depth : in Natural); procedure Create_Frame (Depth : in Natural) is use type MAT.Types.Target_Addr; use type MAT.Events.Frame_Table; F : Frame_Type; begin Pc (Depth) := MAT.Types.Target_Addr (Depth); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; Insert (Root, Pc (1 .. Depth), F); Pc (Depth) := MAT.Types.Target_Addr (Depth) + 1000; Insert (Root, Pc (1 .. Depth), F); if Depth < Pc'Last then Create_Frame (Depth + 1); end if; declare Read_Pc : Frame_Table := Backtrace (F); begin T.Assert (Read_Pc = Pc (1 .. Depth), "Frames.backtrace (same as inserted)"); if Verbose then for I in Read_Pc'Range loop Ada.Text_IO.Put (" " & MAT.Types.Target_Addr'Image (Read_Pc (I))); end loop; Ada.Text_IO.New_Line; end if; end; end Create_Frame; begin Create_Frame (1); if Verbose then MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); end if; Destroy (Root); end Test_Complex_Frames; -- ------------------------------ -- Test allocating and releasing frames. -- ------------------------------ procedure Test_Release_Frames (T : in out Test) is Root : Frame_Type := Create_Root; F1 : Frame_Type; F2 : Frame_Type; F3 : Frame_Type; begin Insert (Root, Frame_1_1, F1); T.Assert (Root.Used > 0, "Insert must increment the root used count"); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_2, F2); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Insert (Root, Frame_1_3, F3); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Output, "Release frame F1"); Release (F1); MAT.Frames.Print (Ada.Text_IO.Standard_Output, Root); T.Assert (F2.Used > 0, "Release must not change other frames"); T.Assert (Root.Used > 0, "Release must not change root frame"); Destroy (Root); end Test_Release_Frames; end MAT.Frames.Tests;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4ee2b0e8eccc5a6ed7099ab2817e6df6ba59c0f2
src/util-texts-builders.ads
src/util-texts-builders.ads
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- 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.Finalization; -- == Description == -- The <tt>Util.Texts.Builders</tt> generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The <tt>Builder</tt> type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an <tt>Append</tt> procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the <tt>Iterate</tt> operation that allows to get the content -- collected by the builder. When using the <tt>Iterate</tt> operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- == Example == -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that recieves -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the <tt>Iterate</tt> operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- generic type Element_Type is (<>); type Input is array (Positive range <>) of Element_Type; Chunk_Size : Positive := 80; package Util.Texts.Builders is pragma Preelaborate; type Builder (Len : Positive) is limited private; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Input); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Element_Type); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Input; private pragma Inline (Length); pragma Inline (Iterate); type Block; type Block_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Block_Access; Last : Natural := 0; Content : Input (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Block_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Block (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); end Util.Texts.Builders;
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- 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.Finalization; -- == Description == -- The <tt>Util.Texts.Builders</tt> generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The <tt>Builder</tt> type holds a list of chunks into which texts are appended. -- * The builder type holds an initial chunk whose capacity is defined when the builder -- instance is declared. -- * There is only an <tt>Append</tt> procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the <tt>Iterate</tt> operation that allows to get the content -- collected by the builder. When using the <tt>Iterate</tt> operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- == Example == -- First, instantiate the package for the element type (eg, String): -- -- package String_Builder is new Util.Texts.Builders (Character, String); -- -- Declare the string builder instance with its initial capacity: -- -- Builder : String_Builder.Builder (256); -- -- And append to it: -- -- String_Builder.Append (Builder, "Hello"); -- -- To get the content collected in the builder instance, write a procedure that recieves -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the <tt>Iterate</tt> operation: -- -- String_Builder.Iterate (Builder, Collect'Access); -- generic type Element_Type is (<>); type Input is array (Positive range <>) of Element_Type; Chunk_Size : Positive := 80; package Util.Texts.Builders is pragma Preelaborate; type Builder (Len : Positive) is limited private; -- Get the length of the item builder. function Length (Source : in Builder) return Natural; -- Get the capacity of the builder. function Capacity (Source : in Builder) return Natural; -- Get the builder block size. function Block_Size (Source : in Builder) return Positive; -- Set the block size for the allocation of next chunks. procedure Set_Block_Size (Source : in out Builder; Size : in Positive); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Input); -- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary. procedure Append (Source : in out Builder; New_Item : in Element_Type); -- Clear the source freeing any storage allocated for the buffer. procedure Clear (Source : in out Builder); -- Iterate over the buffer content calling the <tt>Process</tt> procedure with each -- chunk. procedure Iterate (Source : in Builder; Process : not null access procedure (Chunk : in Input)); -- Get the buffer content as an array. function To_Array (Source : in Builder) return Input; -- Return the content starting from the tail and up to <tt>Length</tt> items. function Tail (Source : in Builder; Length : in Natural) return Input; private pragma Inline (Length); pragma Inline (Iterate); type Block; type Block_Access is access all Block; type Block (Len : Positive) is limited record Next_Block : Block_Access; Last : Natural := 0; Content : Input (1 .. Len); end record; type Builder (Len : Positive) is new Ada.Finalization.Limited_Controlled with record Current : Block_Access; Block_Size : Positive := Chunk_Size; Length : Natural := 0; First : aliased Block (Len); end record; pragma Finalize_Storage_Only (Builder); -- Setup the builder. overriding procedure Initialize (Source : in out Builder); -- Finalize the builder releasing the storage. overriding procedure Finalize (Source : in out Builder); end Util.Texts.Builders;
Declare the Tail function
Declare the Tail function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util