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
0b39675e20e0ef590a7b0971bb14e84c36450a8a
src/gen-model-mappings.adb
src/gen-model-mappings.adb
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); elsif Name = "isNullable" then return Util.Beans.Objects.To_Object (From.Nullable); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_FLOAT => return "float"; when T_ENTITY_TYPE => return "entity_type"; when T_BLOB => return "blob"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; -- ------------------------------ -- Get the type name according to the mapping definition. -- ------------------------------ function Get_Type_Name (Name : in Ada.Strings.Unbounded.Unbounded_String) return String is T : constant Mapping_Definition_Access := Find_Type (Name, False); begin if T = null then return To_String (Name); else return To_String (T.Target); end if; end Get_Type_Name; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015, 2018, 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.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER or From.Kind = T_ENTITY_TYPE); elsif Name = "isFloat" then return Util.Beans.Objects.To_Object (From.Kind = T_FLOAT); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); elsif Name = "isNullable" then return Util.Beans.Objects.To_Object (From.Nullable); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Get the type name. -- ------------------------------ function Get_Type_Name (From : Mapping_Definition) return String is begin case From.Kind is when T_BOOLEAN => return "boolean"; when T_INTEGER => return "integer"; when T_DATE => return "date"; when T_IDENTIFIER => return "identifier"; when T_STRING => return "string"; when T_FLOAT => return "float"; when T_ENTITY_TYPE => return "entity_type"; when T_BLOB => return "blob"; when T_ENUM => return From.Get_Name; when others => return From.Get_Name; end case; end Get_Type_Name; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; -- ------------------------------ -- Get the type name according to the mapping definition. -- ------------------------------ function Get_Type_Name (Name : in Ada.Strings.Unbounded.Unbounded_String) return String is T : constant Mapping_Definition_Access := Find_Type (Name, False); begin if T = null then return To_String (Name); else return To_String (T.Target); end if; end Get_Type_Name; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Mapping.Set_Name (From); Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; Mapping.Allow_Null.Nullable := True; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
Add isFloat attribute to the type mapping
Add isFloat attribute to the type mapping
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
5056237913b6d571020b372151c1c1ef5ba79bc2
src/natools-web-simple_pages.adb
src/natools-web-simple_pages.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014-2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar; with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Simple_Pages; with Natools.Web.Error_Pages; with Natools.Web.Exchanges; with Natools.Web.Fallback_Render; package body Natools.Web.Simple_Pages is Expiration_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!expire"); procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom); procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Meaningless_Type, Execute); procedure Render_Page is new S_Expressions.Interpreter_Loop (Sites.Exchange, Page_Data, Render, Append); --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); package Components renames Natools.Static_Maps.Web.Simple_Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Comment_List => Data.Comment_List.Set (Arguments); when Components.Dates => Containers.Set_Dates (Data.Dates, Arguments); when Components.Elements => Containers.Set_Expressions (Data.Elements, Arguments); when Components.Tags => Tags.Append (Data.Tags, Arguments); end case; end Execute; ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom) is pragma Unreferenced (Page); begin Exchange.Append (Data); end Append; procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Render_Date (Log_Error : in Boolean); procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Page); end Re_Enter; procedure Render_Date (Log_Error : in Boolean) is begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Cursor : constant Containers.Date_Maps.Cursor := Page.Dates.Find (Arguments.Current_Atom); begin if not Containers.Date_Maps.Has_Element (Cursor) then if Log_Error then Log (Severities.Error, "Unable to find date """ & S_Expressions.To_String (Arguments.Current_Atom) & """ in page date map"); end if; return; end if; Arguments.Next; declare Item : constant Containers.Date := Containers.Date_Maps.Element (Cursor); begin S_Expressions.Templates.Dates.Render (Exchange, Arguments, Item.Time, Item.Offset); end; end; end if; end Render_Date; package Commands renames Natools.Static_Maps.Web.Simple_Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => Fallback_Render (Exchange, Name, Arguments, "simple page", Re_Enter'Access, Page.Elements); when Commands.Comment_List => Comments.Render (Exchange, Page.Comment_List, Arguments); when Commands.Date => Render_Date (True); when Commands.My_Tags => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Prefix : constant S_Expressions.Atom := Arguments.Current_Atom; begin Arguments.Next; Tags.Render (Exchange, Page.Tags, Exchange.Site.Get_Tags, Prefix, Arguments); end; end if; when Commands.If_No_Date => if Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Page.Dates.Contains (Arguments.Current_Atom) then Arguments.Next; Render_Page (Arguments, Exchange, Page); end if; when Commands.Optional_Date => Render_Date (False); when Commands.Path => Exchange.Append (Page.Web_Path.Query); when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Page.Tags); end case; end Render; ------------------------- -- Page_Data Interface -- ------------------------- not overriding procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ---------------------- -- Public Interface -- ---------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data; Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); begin Page.Self := Tags.Visible_Access (Page); Read_Page (Expression, Page.all, Meaningless_Value); return Result; end Create; function Create (File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data' (File_Path => File_Path, Web_Path => Web_Path, Tags => <>, Self => null, Comment_List | Elements | Dates => <>); Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); begin Page.Self := Tags.Visible_Access (Page); Create_Page : declare Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path.Query)); begin Read_Page (Reader, Page.all, Meaningless_Value); end Create_Page; return Result; end Create; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object.Ref.Query.Data.all); end Render; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Data; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object); end Render; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom) is use type S_Expressions.Offset; begin if Extra_Path'Length = 9 and then S_Expressions.To_String (Extra_Path) = "/comments" then Object.Ref.Update.Comment_List.Respond (Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last)); return; end if; if Extra_Path'Length > 0 then return; end if; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Expression : S_Expressions.Caches.Cursor; begin Check_Method : declare use Exchanges; Allowed : Boolean; begin Error_Pages.Check_Method (Exchange, (GET, HEAD), Allowed); if not Allowed then return; end if; end Check_Method; Expression := Exchange.Site.Get_Template (Accessor.Data.Elements, Expression, Exchange.Site.Default_Template, Lookup_Element => True, Lookup_Template => True, Lookup_Name => True); Render_Page (Expression, Exchange, Accessor.Data.all); end; end Respond; ----------------------- -- Page Constructors -- ----------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is Page : constant Page_Ref := Create (Object.File_Path, S_Expressions.Atom_Ref_Constructors.Create (Path)); begin Expiration_Check : declare use type Ada.Calendar.Time; Accessor : constant Data_Refs.Accessor := Page.Ref.Query; Cursor : constant Containers.Date_Maps.Cursor := Accessor.Dates.Find (Expiration_Date_Key); begin if Containers.Date_Maps.Has_Element (Cursor) and then Containers.Date_Maps.Element (Cursor).Time < Ada.Calendar.Clock then return; end if; end Expiration_Check; Sites.Insert (Builder, Path, Page); Sites.Insert (Builder, Page.Get_Tags, Page); declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path); end; end Load; procedure Register_Loader (Site : in out Sites.Site) is begin Site.Register ("simple-page", Create'Access); end Register_Loader; end Natools.Web.Simple_Pages;
------------------------------------------------------------------------------ -- Copyright (c) 2014-2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Calendar; with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Simple_Pages; with Natools.Web.Error_Pages; with Natools.Web.Exchanges; with Natools.Web.Fallback_Render; package body Natools.Web.Simple_Pages is Expiration_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!expire"); Publication_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!publish"); procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom); procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Meaningless_Type, Execute); procedure Render_Page is new S_Expressions.Interpreter_Loop (Sites.Exchange, Page_Data, Render, Append); --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); package Components renames Natools.Static_Maps.Web.Simple_Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Comment_List => Data.Comment_List.Set (Arguments); when Components.Dates => Containers.Set_Dates (Data.Dates, Arguments); when Components.Elements => Containers.Set_Expressions (Data.Elements, Arguments); when Components.Tags => Tags.Append (Data.Tags, Arguments); end case; end Execute; ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom) is pragma Unreferenced (Page); begin Exchange.Append (Data); end Append; procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Render_Date (Log_Error : in Boolean); procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Page); end Re_Enter; procedure Render_Date (Log_Error : in Boolean) is begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Cursor : constant Containers.Date_Maps.Cursor := Page.Dates.Find (Arguments.Current_Atom); begin if not Containers.Date_Maps.Has_Element (Cursor) then if Log_Error then Log (Severities.Error, "Unable to find date """ & S_Expressions.To_String (Arguments.Current_Atom) & """ in page date map"); end if; return; end if; Arguments.Next; declare Item : constant Containers.Date := Containers.Date_Maps.Element (Cursor); begin S_Expressions.Templates.Dates.Render (Exchange, Arguments, Item.Time, Item.Offset); end; end; end if; end Render_Date; package Commands renames Natools.Static_Maps.Web.Simple_Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => Fallback_Render (Exchange, Name, Arguments, "simple page", Re_Enter'Access, Page.Elements); when Commands.Comment_List => Comments.Render (Exchange, Page.Comment_List, Arguments); when Commands.Date => Render_Date (True); when Commands.My_Tags => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Prefix : constant S_Expressions.Atom := Arguments.Current_Atom; begin Arguments.Next; Tags.Render (Exchange, Page.Tags, Exchange.Site.Get_Tags, Prefix, Arguments); end; end if; when Commands.If_No_Date => if Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Page.Dates.Contains (Arguments.Current_Atom) then Arguments.Next; Render_Page (Arguments, Exchange, Page); end if; when Commands.Optional_Date => Render_Date (False); when Commands.Path => Exchange.Append (Page.Web_Path.Query); when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Page.Tags); end case; end Render; ------------------------- -- Page_Data Interface -- ------------------------- not overriding procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ---------------------- -- Public Interface -- ---------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data; Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); begin Page.Self := Tags.Visible_Access (Page); Read_Page (Expression, Page.all, Meaningless_Value); return Result; end Create; function Create (File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data' (File_Path => File_Path, Web_Path => Web_Path, Tags => <>, Self => null, Comment_List | Elements | Dates => <>); Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); begin Page.Self := Tags.Visible_Access (Page); Create_Page : declare Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path.Query)); begin Read_Page (Reader, Page.all, Meaningless_Value); end Create_Page; return Result; end Create; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object.Ref.Query.Data.all); end Render; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Data; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object); end Render; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom) is use type S_Expressions.Offset; begin if Extra_Path'Length = 9 and then S_Expressions.To_String (Extra_Path) = "/comments" then Object.Ref.Update.Comment_List.Respond (Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last)); return; end if; if Extra_Path'Length > 0 then return; end if; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Expression : S_Expressions.Caches.Cursor; begin Check_Method : declare use Exchanges; Allowed : Boolean; begin Error_Pages.Check_Method (Exchange, (GET, HEAD), Allowed); if not Allowed then return; end if; end Check_Method; Expression := Exchange.Site.Get_Template (Accessor.Data.Elements, Expression, Exchange.Site.Default_Template, Lookup_Element => True, Lookup_Template => True, Lookup_Name => True); Render_Page (Expression, Exchange, Accessor.Data.all); end; end Respond; ----------------------- -- Page Constructors -- ----------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is Page : constant Page_Ref := Create (Object.File_Path, S_Expressions.Atom_Ref_Constructors.Create (Path)); begin Time_Check : declare use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Accessor : constant Data_Refs.Accessor := Page.Ref.Query; Cursor : Containers.Date_Maps.Cursor := Accessor.Dates.Find (Expiration_Date_Key); begin if Containers.Date_Maps.Has_Element (Cursor) and then Containers.Date_Maps.Element (Cursor).Time < Now then return; end if; Cursor := Accessor.Dates.Find (Publication_Date_Key); if Containers.Date_Maps.Has_Element (Cursor) and then Containers.Date_Maps.Element (Cursor).Time >= Now then return; end if; end Time_Check; Sites.Insert (Builder, Path, Page); Sites.Insert (Builder, Page.Get_Tags, Page); declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path); end; end Load; procedure Register_Loader (Site : in out Sites.Site) is begin Site.Register ("simple-page", Create'Access); end Register_Loader; end Natools.Web.Simple_Pages;
add a special date used to mark page publication time
simple_pages: add a special date used to mark page publication time
Ada
isc
faelys/natools-web,faelys/natools-web
699bbd10da12e434ba3f6ffb1bcfbf83ec7b0104
src/results/adabase-results.ads
src/results/adabase-results.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with CommonText; with Ada.Calendar; with Ada.Strings.Wide_Unbounded; with Ada.Strings.Wide_Wide_Unbounded; package AdaBase.Results is package CT renames CommonText; package AC renames Ada.Calendar; package SUW renames Ada.Strings.Wide_Unbounded; package SUWW renames Ada.Strings.Wide_Wide_Unbounded; subtype textual is CT.Text; subtype textwide is SUW.Unbounded_Wide_String; subtype textsuper is SUWW.Unbounded_Wide_Wide_String; TARGET_TYPE_TOO_NARROW : exception; CONVERSION_FAILED : exception; UNSUPPORTED_CONVERSION : exception; COLUMN_DOES_NOT_EXIST : exception; CONSTRUCTOR_DO_NOT_USE : exception; ------------------------------------------- -- Supported Field Types (Standardized) -- ------------------------------------------- type nbyte1 is mod 2 ** 8; type nbyte2 is mod 2 ** 16; type nbyte3 is mod 2 ** 24; type nbyte4 is mod 2 ** 32; type nbyte8 is mod 2 ** 64; type byte8 is range -2 ** 63 .. 2 ** 63 - 1; type byte4 is range -2 ** 31 .. 2 ** 31 - 1; type byte3 is range -2 ** 23 .. 2 ** 23 - 1; type byte2 is range -2 ** 15 .. 2 ** 15 - 1; type byte1 is range -2 ** 7 .. 2 ** 7 - 1; type real9 is digits 9; type real18 is digits 18; subtype nbyte0 is Boolean; type chain is array (Positive range <>) of nbyte1; type enumtype is record enumeration : textual; index : Natural; end record; type settype is array (Positive range <>) of enumtype; type nbyte0_access is access all nbyte0; type nbyte1_access is access all nbyte1; type nbyte2_access is access all nbyte2; type nbyte3_access is access all nbyte3; type nbyte4_access is access all nbyte4; type nbyte8_access is access all nbyte8; type byte1_access is access all byte1; type byte2_access is access all byte2; type byte3_access is access all byte3; type byte4_access is access all byte4; type byte8_access is access all byte8; type real9_access is access all real9; type real18_access is access all real18; type str1_access is access all textual; type str2_access is access all textwide; type str4_access is access all textsuper; type time_access is access all AC.Time; type chain_access is access all chain; -- stored as access type enum_access is access all enumtype; type settype_access is access all settype; -- stored as access ------------------------------------------------ -- CONSTANTS FOR PARAMETER TYPE DEFINITIONS -- ------------------------------------------------ PARAM_IS_BOOLEAN : constant nbyte0 := False; PARAM_IS_NBYTE_1 : constant nbyte1 := 0; PARAM_IS_NBYTE_2 : constant nbyte2 := 0; PARAM_IS_NBYTE_3 : constant nbyte3 := 0; PARAM_IS_NBYTE_4 : constant nbyte4 := 0; PARAM_IS_NBYTE_8 : constant nbyte8 := 0; PARAM_IS_BYTE_1 : constant byte1 := 0; PARAM_IS_BYTE_2 : constant byte2 := 0; PARAM_IS_BYTE_3 : constant byte3 := 0; PARAM_IS_BYTE_4 : constant byte4 := 0; PARAM_IS_BYTE_8 : constant byte8 := 0; PARAM_IS_REAL_9 : constant real9 := 0.0; PARAM_IS_REAL_18 : constant real18 := 0.0; PARAM_IS_CHAIN : constant chain := (1 .. 1 => 0); PARAM_IS_ENUM : constant enumtype := (CT.blank, 0); PARAM_IS_SET : constant settype := (1 .. 1 => (CT.blank, 0)); PARAM_IS_TEXTUAL : constant textual := CT.blank; PARAM_IS_TEXTWIDE : constant textwide := SUW.Null_Unbounded_Wide_String; PARAM_IS_TEXTSUPER : constant textsuper := SUWW.Null_Unbounded_Wide_Wide_String; PARAM_IS_TIMESTAMP : constant AC.Time := AC.Time_Of (AC.Year_Number'First, AC.Month_Number'First, AC.Day_Number'First); end AdaBase.Results;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with CommonText; with Ada.Calendar; with Ada.Strings.Wide_Unbounded; with Ada.Strings.Wide_Wide_Unbounded; package AdaBase.Results is package CT renames CommonText; package AC renames Ada.Calendar; package SUW renames Ada.Strings.Wide_Unbounded; package SUWW renames Ada.Strings.Wide_Wide_Unbounded; subtype textual is CT.Text; subtype textwide is SUW.Unbounded_Wide_String; subtype textsuper is SUWW.Unbounded_Wide_Wide_String; TARGET_TYPE_TOO_NARROW : exception; CONVERSION_FAILED : exception; UNSUPPORTED_CONVERSION : exception; COLUMN_DOES_NOT_EXIST : exception; CONSTRUCTOR_DO_NOT_USE : exception; ------------------------------------------- -- Supported Field Types (Standardized) -- ------------------------------------------- type nbyte1 is mod 2 ** 8; type nbyte2 is mod 2 ** 16; type nbyte3 is mod 2 ** 24; type nbyte4 is mod 2 ** 32; type nbyte8 is mod 2 ** 64; type byte8 is range -2 ** 63 .. 2 ** 63 - 1; type byte4 is range -2 ** 31 .. 2 ** 31 - 1; type byte3 is range -2 ** 23 .. 2 ** 23 - 1; type byte2 is range -2 ** 15 .. 2 ** 15 - 1; type byte1 is range -2 ** 7 .. 2 ** 7 - 1; type real9 is digits 9; type real18 is digits 18; subtype nbyte0 is Boolean; type enumtype is record enumeration : textual; index : Natural; end record; type settype is array (Positive range <>) of enumtype; type chain is array (Positive range <>) of nbyte1; type nbyte0_access is access all nbyte0; type nbyte1_access is access all nbyte1; type nbyte2_access is access all nbyte2; type nbyte3_access is access all nbyte3; type nbyte4_access is access all nbyte4; type nbyte8_access is access all nbyte8; type byte1_access is access all byte1; type byte2_access is access all byte2; type byte3_access is access all byte3; type byte4_access is access all byte4; type byte8_access is access all byte8; type real9_access is access all real9; type real18_access is access all real18; type str1_access is access all textual; type str2_access is access all textwide; type str4_access is access all textsuper; type time_access is access all AC.Time; type chain_access is access all chain; -- stored as access type enum_access is access all enumtype; type settype_access is access all settype; -- stored as access blank_string : constant textual := CT.blank; blank_wstring : constant textwide := SUW.Null_Unbounded_Wide_String; blank_wwstring : constant textsuper := SUWW.Null_Unbounded_Wide_Wide_String; ------------------------------------------------ -- CONSTANTS FOR PARAMETER TYPE DEFINITIONS -- ------------------------------------------------ PARAM_IS_BOOLEAN : constant nbyte0 := False; PARAM_IS_NBYTE_1 : constant nbyte1 := 0; PARAM_IS_NBYTE_2 : constant nbyte2 := 0; PARAM_IS_NBYTE_3 : constant nbyte3 := 0; PARAM_IS_NBYTE_4 : constant nbyte4 := 0; PARAM_IS_NBYTE_8 : constant nbyte8 := 0; PARAM_IS_BYTE_1 : constant byte1 := 0; PARAM_IS_BYTE_2 : constant byte2 := 0; PARAM_IS_BYTE_3 : constant byte3 := 0; PARAM_IS_BYTE_4 : constant byte4 := 0; PARAM_IS_BYTE_8 : constant byte8 := 0; PARAM_IS_REAL_9 : constant real9 := 0.0; PARAM_IS_REAL_18 : constant real18 := 0.0; PARAM_IS_CHAIN : constant chain := (1 .. 1 => 0); PARAM_IS_ENUM : constant enumtype := (CT.blank, 0); PARAM_IS_SET : constant settype := (1 .. 1 => (CT.blank, 0)); PARAM_IS_TEXTUAL : constant textual := blank_string; PARAM_IS_TEXTWIDE : constant textwide := blank_wstring; PARAM_IS_TEXTSUPER : constant textsuper := blank_wwstring; PARAM_IS_TIMESTAMP : constant AC.Time := AC.Time_Of (AC.Year_Number'First, AC.Month_Number'First, AC.Day_Number'First); end AdaBase.Results;
Define blank constants variants
Results: Define blank constants variants
Ada
isc
jrmarino/AdaBase
8890a3d6da408ee24937a8c9236a49a01f9bcf4d
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 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. -- When a prefix is specified, only the properties starting with -- the prefix are returned. function Get_Names (Self : in Manager; Prefix : in String := "") 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; Prefix : in String) 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. -- When a prefix is specified, only the properties starting with -- the prefix are returned. function Get_Names (Self : in Manager; Prefix : in String := "") 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; Prefix : in String) 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; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
Adjust and Finalize are overriding
Adjust and Finalize are overriding
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d15798308458957049896ef391a507febab6e4bb
src/util-dates-iso8601.adb
src/util-dates-iso8601.adb
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- 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. ----------------------------------------------------------------------- package body Util.Dates.ISO8601 is -- ------------------------------ -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. -- ------------------------------ function Value (Date : in String) return Ada.Calendar.Time is use Ada.Calendar; Result : Date_Record; begin if Date'Length < 4 then raise Constraint_Error with "Invalid date"; end if; Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3)); if Date'Length = 4 then -- ISO8601 date: YYYY Result.Month := 1; Result.Month_Day := 1; elsif Date'Length = 7 and Date (Date'First + 4) = '-' then -- ISO8601 date: YYYY-MM Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last)); Result.Month_Day := 1; elsif Date'Length = 8 then -- ISO8601 date: YYYYMMDD Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5)); Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7)); elsif Date'Length >= 9 and then Date (Date'First + 4) = '-' and then Date (Date'First + 7) = '-' then -- ISO8601 date: YYYY-MM-DD Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6)); Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9)); else raise Constraint_Error with "invalid date"; end if; return Ada.Calendar.Formatting.Time_Of (Year => Result.Year, Month => Result.Month, Day => Result.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0); end Value; -- ------------------------------ -- Return the ISO8601 date. -- ------------------------------ function Image (Date : in Ada.Calendar.Time) return String is D : Date_Record; begin Split (D, Date); return Image (D); end Image; function Image (Date : in Date_Record) return String is To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 10) := "0000-00-00"; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); return Result; end Image; end Util.Dates.ISO8601;
----------------------------------------------------------------------- -- util-dates-iso8601 -- ISO8601 dates -- Copyright (C) 2011, 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. ----------------------------------------------------------------------- package body Util.Dates.ISO8601 is -- ------------------------------ -- Parses an ISO8601 date and return it as a calendar time. -- Raises Constraint_Error if the date format is not recognized. -- ------------------------------ function Value (Date : in String) return Ada.Calendar.Time is use Ada.Calendar; Result : Date_Record; begin if Date'Length < 4 then raise Constraint_Error with "Invalid date"; end if; Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3)); if Date'Length = 4 then -- ISO8601 date: YYYY Result.Month := 1; Result.Month_Day := 1; elsif Date'Length = 7 and Date (Date'First + 4) = '-' then -- ISO8601 date: YYYY-MM Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last)); Result.Month_Day := 1; elsif Date'Length = 8 then -- ISO8601 date: YYYYMMDD Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5)); Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7)); elsif Date'Length >= 9 and then Date (Date'First + 4) = '-' and then Date (Date'First + 7) = '-' then -- ISO8601 date: YYYY-MM-DD Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6)); Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9)); else raise Constraint_Error with "invalid date"; end if; return Ada.Calendar.Formatting.Time_Of (Year => Result.Year, Month => Result.Month, Day => Result.Month_Day, Hour => 0, Minute => 0, Second => 0, Sub_Second => 0.0); end Value; -- ------------------------------ -- Return the ISO8601 date. -- ------------------------------ function Image (Date : in Ada.Calendar.Time) return String is D : Date_Record; begin Split (D, Date); return Image (D); end Image; function Image (Date : in Date_Record) return String is To_Char : constant array (0 .. 9) of Character := "0123456789"; Result : String (1 .. 10) := "0000-00-00"; begin Result (1) := To_Char (Date.Year / 1000); Result (2) := To_Char (Date.Year / 100 mod 10); Result (3) := To_Char (Date.Year / 10 mod 10); Result (4) := To_Char (Date.Year mod 10); Result (6) := To_Char (Date.Month / 10); Result (7) := To_Char (Date.Month mod 10); Result (9) := To_Char (Date.Month_Day / 10); Result (10) := To_Char (Date.Month_Day mod 10); return Result; end Image; end Util.Dates.ISO8601;
Fix compilation style warning
Fix compilation style warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
86982f45b04ff19da9346874ef2b969b6ba5a604
src/ado-schemas-entities.ads
src/ado-schemas-entities.ads
----------------------------------------------------------------------- -- 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;
----------------------------------------------------------------------- -- 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; with ADO.Caches; 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;
Add missing with clause ADO.Caches
Add missing with clause ADO.Caches
Ada
apache-2.0
stcarrez/ada-ado
37271ef46078b014ec2a74654da413ac34435d4a
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.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;
----------------------------------------------------------------------- -- 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 Log.Debug ("Use wallet property {0} as {1}", Name, Name (Name'First + Self.Length .. Name'Last)); 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;
Add some debugging trace
Add some debugging trace
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
83a5e4873b6834a110d0e730d868dacfafea926d
src/asf-components-html-factory.adb
src/asf-components-html-factory.adb
----------------------------------------------------------------------- -- html-factory -- Factory for HTML UI Components -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Html.Text; with ASF.Components.Html.Lists; with ASF.Views.Nodes; package body ASF.Components.Html.Factory is function Create_Output return UIComponent_Access; function Create_Label return UIComponent_Access; function Create_List return UIComponent_Access; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutput; end Create_Output; -- ------------------------------ -- Create a label component -- ------------------------------ function Create_Label return UIComponent_Access is begin return new ASF.Components.Html.Text.UILabel; end Create_Label; -- ------------------------------ -- Create an UIList component -- ------------------------------ function Create_List return UIComponent_Access is begin return new ASF.Components.Html.Lists.UIList; end Create_List; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/html"; OUTPUT_TAG : aliased constant String := "output"; LABEL_TAG : aliased constant String := "label"; LIST_TAG : aliased constant String := "list"; Html_Bindings : aliased constant ASF.Factory.Binding_Array := (2 => (Name => OUTPUT_TAG'Access, Component => Create_Output'Access, Tag => Create_Component_Node'Access), 0 => (Name => LABEL_TAG'Access, Component => Create_Label'Access, Tag => Create_Component_Node'Access), 1 => (Name => LIST_TAG'Access, Component => Create_List'Access, Tag => Create_Component_Node'Access) ); Html_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Html_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Html_Factory'Access; end Definition; begin ASF.Factory.Check (Html_Factory); end ASF.Components.Html.Factory;
----------------------------------------------------------------------- -- html-factory -- Factory for HTML UI Components -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Html.Text; with ASF.Components.Html.Lists; with ASF.Components.Html.Links; with ASF.Views.Nodes; package body ASF.Components.Html.Factory is function Create_Output return UIComponent_Access; function Create_Output_Link return UIComponent_Access; function Create_Label return UIComponent_Access; function Create_List return UIComponent_Access; -- ------------------------------ -- Create an UIOutput component -- ------------------------------ function Create_Output return UIComponent_Access is begin return new ASF.Components.Html.Text.UIOutput; end Create_Output; -- ------------------------------ -- Create an UIOutputLink component -- ------------------------------ function Create_Output_Link return UIComponent_Access is begin return new ASF.Components.Html.Links.UIOutputLink; end Create_Output_Link; -- ------------------------------ -- Create a label component -- ------------------------------ function Create_Label return UIComponent_Access is begin return new ASF.Components.Html.Text.UILabel; end Create_Label; -- ------------------------------ -- Create an UIList component -- ------------------------------ function Create_List return UIComponent_Access is begin return new ASF.Components.Html.Lists.UIList; end Create_List; use ASF.Views.Nodes; URI : aliased constant String := "http://java.sun.com/jsf/html"; OUTPUT_TEXT_TAG : aliased constant String := "outputText"; OUTPUT_LINK_TAG : aliased constant String := "outputLink"; LABEL_TAG : aliased constant String := "label"; LIST_TAG : aliased constant String := "list"; Html_Bindings : aliased constant ASF.Factory.Binding_Array := (4 => (Name => OUTPUT_TEXT_TAG'Access, Component => Create_Output'Access, Tag => Create_Component_Node'Access), 1 => (Name => LABEL_TAG'Access, Component => Create_Label'Access, Tag => Create_Component_Node'Access), 2 => (Name => LIST_TAG'Access, Component => Create_List'Access, Tag => Create_Component_Node'Access), 3 => (Name => OUTPUT_LINK_TAG'Access, Component => Create_Output_Link'Access, Tag => Create_Component_Node'Access) ); Html_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Html_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Html_Factory'Access; end Definition; begin ASF.Factory.Check (Html_Factory); end ASF.Components.Html.Factory;
Update the jsf components factory
Update the jsf components factory
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
0b91c91b85bdb6c8160154cc3b51c28fc1fba048
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with 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; 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") 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; 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 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_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); 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] " & "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"); Put_Line (" -tool Generate a command line tool"); Put_Line (" -ado Generate a database tool operation for ADO"); end Help; end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with 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; 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") 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; 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 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_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); 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] " & "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"); end Help; end Gen.Commands.Project;
Update the create-project help message
Update the create-project help message
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
9facc70bf9714b20fd204f4bb204854e2f83d59a
testutil/ahven/ahven-xml_runner.adb
testutil/ahven/ahven-xml_runner.adb
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Trim (Get_Message (Info), Ada.Strings.Both)); Put (File, ">"); Put_Line (File, Get_Message (Info)); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
Fix other issues when a message contains unclosed XML entities.
Fix other issues when a message contains unclosed XML entities.
Ada
apache-2.0
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
7eb03de53754e5e09b76e59a0e095186d4bc9d0a
awa/regtests/awa-users-tests.adb
awa/regtests/awa-users-tests.adb
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with ASF.Tests; with AWA.Tests; with AWA.Users.Models; with AWA.Users.Services.Tests.Helpers; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_UUID & "@gmail.com"; Principal : Services.Tests.Helpers.Test_User; begin Services.Tests.Helpers.Initialize (Principal); Do_Get (Request, Reply, "/users/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("first_name", "joe"); Request.Set_Parameter ("last_name", "dalton"); Request.Set_Parameter ("register", "1"); Do_Post (Request, Reply, "/users/register.html", "create-user-2.html"); Assert (T, Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. Assert (T, Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key); Assert (T, not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/users/validate.html", "validate-user-1.html"); end; -- Check that the user is logged and we have a user principal now. Assert (T, Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/users/login.html", "login-user-1.html"); -- Check that the user is NOT logged. Assert (T, Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("login", "1"); Do_Post (Request, Reply, "/users/login.html", "login-user-2.html"); Assert (T, Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is logged and we have a user principal now. Assert (T, Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "[email protected]"; begin Do_Get (Request, Reply, "/users/lost-password.html", "lost-password-1.html"); Request.Set_Parameter ("email", Email); Do_Post (Request, Reply, "/users/lost-password.html", "lost-password-2.html"); Assert (T, Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Now, get the access key and simulate a click on the reset password link. declare Principal : Services.Tests.Helpers.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key); Assert (T, not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/users/reset-password.html", "reset-password-1.html"); -- Post the reset password Request.Set_Parameter ("password", "asd"); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/users/reset-password.html", "reset-password-2.html"); Assert (T, Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is logged and we have a user principal now. Assert (T, Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Test_Reset_Password_User; end AWA.Users.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Test_Caller; with ASF.Tests; with AWA.Tests; with AWA.Users.Models; with AWA.Users.Services.Tests.Helpers; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; package body AWA.Users.Tests is use ASF.Tests; use AWA.Tests; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_UUID & "@gmail.com"; Principal : Services.Tests.Helpers.Test_User; begin Services.Tests.Helpers.Initialize (Principal); Do_Get (Request, Reply, "/users/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("first_name", "joe"); Request.Set_Parameter ("last_name", "dalton"); Request.Set_Parameter ("register", "1"); Do_Post (Request, Reply, "/users/register.html", "create-user-2.html"); Assert (T, Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. Assert (T, Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key); Assert (T, not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/users/validate.html", "validate-user-1.html"); end; -- Check that the user is logged and we have a user principal now. Assert (T, Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Create_User; procedure Test_Logout_User (T : in out Test) is begin null; end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/users/login.html", "login-user-1.html"); -- Check that the user is NOT logged. Assert (T, Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("login", "1"); Do_Post (Request, Reply, "/users/login.html", "login-user-2.html"); Assert (T, Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is logged and we have a user principal now. Assert (T, Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is use type ASF.Principals.Principal_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Email : constant String := "[email protected]"; Principal : Services.Tests.Helpers.Test_User; begin Services.Tests.Helpers.Initialize (Principal); Do_Get (Request, Reply, "/users/lost-password.html", "lost-password-1.html"); Request.Set_Parameter ("email", Email); Do_Post (Request, Reply, "/users/lost-password.html", "lost-password-2.html"); Assert (T, Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Now, get the access key and simulate a click on the reset password link. declare Key : AWA.Users.Models.Access_Key_Ref; begin Services.Tests.Helpers.Find_Access_Key (Principal, Email, Key); Assert (T, not Key.Is_Null, "There is no access key associated with the user"); Request.Set_Parameter ("key", Key.Get_Access_Key); Do_Get (Request, Reply, "/users/reset-password.html", "reset-password-1.html"); -- Post the reset password Request.Set_Parameter ("password", "asd"); Request.Set_Parameter ("reset-password", "1"); Do_Post (Request, Reply, "/users/reset-password.html", "reset-password-2.html"); Assert (T, Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response"); -- Check that the user is logged and we have a user principal now. Assert (T, Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Test_Reset_Password_User; end AWA.Users.Tests;
Update lost password unit test
Update lost password unit test
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
4ba239c5c58fc2875ea69a012654101433866910
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 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;
----------------------------------------------------------------------- -- awa-users-principals -- User principals -- 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. ----------------------------------------------------------------------- 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; -- ------------------------------ -- 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;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9dcdbb4fbec5c6406b4829774fdc7aeebcecd468
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Declare the Frame_Information procedure and protected operation
Declare the Frame_Information procedure and protected operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2a02b67446f92180d729a2afcf2433675251c119
awa/regtests/awa-modules-tests.adb
awa/regtests/awa-modules-tests.adb
----------------------------------------------------------------------- -- awa-modules-tests - Unit tests for Modules -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Main; with AWA.Modules.Beans; with AWA.Services.Contexts; package body AWA.Modules.Tests is use Util.Tests; type Test_Module is new AWA.Modules.Module with null record; type Test_Module_Access is access all Test_Module'Class; type Test_Bean is new Util.Beans.Basic.Bean with record Module : Test_Module_Access := null; Name : Util.Beans.Objects.Object; Email : Util.Beans.Objects.Object; end record; type Test_Bean_Access is access all Test_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 Test_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. overriding procedure Set_Value (From : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object); function Create_Form_Bean (Plugin : in Test_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; package Module_Register is new AWA.Modules.Beans (Test_Module, Test_Module_Access); package Caller is new Util.Test_Caller (Test, "AWA.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Modules.Register", Test_Create_Module'Access); Caller.Add_Test (Suite, "Test ASF.Modules.Find_Module", Test_Find_Module'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register", Test_Create_Application_Module'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Application_Module'Access); Caller.Add_Test (Suite, "Test ASF.Navigations.Mappers", Test_Module_Navigation'Access); end Add_Tests; -- ------------------------------ -- 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 Test_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "module" then return Util.Beans.Objects.To_Object (From.Module.Get_Name); elsif Name = "name" then return From.Name; elsif Name = "email" then return From.Email; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Name := Value; elsif Name = "email" then From.Email := Value; end if; end Set_Value; function Create_Form_Bean (Plugin : in Test_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Test_Bean_Access := new Test_Bean; begin Result.Module := Plugin; return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin Log.Info ("Creating application"); T.App := new AWA.Applications.Application; C.Copy (Util.Tests.Get_Properties); C.Set ("app_search_dirs", Util.Tests.Get_Path ("regtests") & ";" & C.Get ("app_search_dirs", "")); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Log.Info ("Releasing application"); Free (T.App); end Tear_Down; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Create_Module (T : in out Test) is M : aliased Test_Module; R : aliased Module_Registry; Ctx : AWA.Services.Contexts.Service_Context; begin Ctx.Set_Context (T.App, null); R.Config.Copy (Util.Tests.Get_Properties); M.App := T.App.all'Access; Register (R'Unchecked_Access, M.App, M'Unchecked_Access, "empty", "uri"); T.Assert_Equals ("empty", M.Get_Name, "Invalid module name"); T.Assert_Equals ("uri", M.Get_URI, "Invalid module uri"); T.Assert (Find_By_Name (R, "empty") = M'Unchecked_Access, "Find_By_Name failed"); T.Assert (Find_By_URI (R, "uri") = M'Unchecked_Access, "Find_By_URI failed"); end Test_Create_Module; -- ------------------------------ -- Test looking for module -- ------------------------------ procedure Test_Find_Module (T : in out Test) is M : aliased Test_Module; Ctx : AWA.Services.Contexts.Service_Context; begin Ctx.Set_Context (T.App, null); M.App := T.App.all'Access; T.App.Register (M'Unchecked_Access, "empty", "uri"); T.Assert (M.Find_Module ("empty") /= null, "Find_Module should not return a null value"); T.Assert (M.Find_Module ("toto") = null, "Find_Module should return null"); end Test_Find_Module; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Application_Module (T : in out Test) is use ASF.Beans; use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); T.Assert_Equals ("test-module", Util.Beans.Objects.To_String (Bean.Get_Value ("module")), "Bean module name"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; M : aliased Test_Module; Ctx : AWA.Services.Contexts.Service_Context; begin Ctx.Set_Context (T.App, null); M.App := T.App.all'Access; Module_Register.Register (Plugin => M, Name => "ASF.Applications.Tests.Form_Bean", Handler => Create_Form_Bean'Access); T.App.Register (M'Unchecked_Access, "test-module", "uri"); T.Assert (M.Find_Module ("test-module") /= null, "Find_Module should not return a null value"); T.Assert (M.Find_Module ("toto") = null, "Find_Module should return null"); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Application_Module; -- ------------------------------ -- Test module and navigation rules -- ------------------------------ procedure Test_Module_Navigation (T : in out Test) is use ASF.Beans; use type Util.Beans.Basic.Readonly_Bean_Access; M : aliased Test_Module; Ctx : AWA.Services.Contexts.Service_Context; begin Ctx.Set_Context (T.App, null); M.App := T.App.all'Access; Module_Register.Register (Plugin => M, Name => "ASF.Applications.Tests.Form_Bean", Handler => Create_Form_Bean'Access); T.App.Register (M'Unchecked_Access, "test-navigations", "uri"); T.Assert (M.Find_Module ("test-navigations") /= null, "Find_Module should not return a null value"); end Test_Module_Navigation; end AWA.Modules.Tests;
----------------------------------------------------------------------- -- awa-modules-tests - Unit tests for Modules -- Copyright (C) 2011, 2012, 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.Beans.Basic; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Main; with AWA.Modules.Beans; with AWA.Services.Contexts; package body AWA.Modules.Tests is use Util.Tests; type Test_Module is new AWA.Modules.Module with null record; type Test_Module_Access is access all Test_Module'Class; type Test_Bean is new Util.Beans.Basic.Bean with record Module : Test_Module_Access := null; Name : Util.Beans.Objects.Object; Email : Util.Beans.Objects.Object; end record; type Test_Bean_Access is access all Test_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 Test_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. overriding procedure Set_Value (From : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object); function Create_Form_Bean (Plugin : in Test_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; package Module_Register is new AWA.Modules.Beans (Test_Module, Test_Module_Access); package Caller is new Util.Test_Caller (Test, "AWA.Modules"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Modules.Register", Test_Create_Module'Access); Caller.Add_Test (Suite, "Test ASF.Modules.Find_Module", Test_Find_Module'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register", Test_Create_Application_Module'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Application_Module'Access); Caller.Add_Test (Suite, "Test ASF.Navigations.Mappers", Test_Module_Navigation'Access); end Add_Tests; -- ------------------------------ -- 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 Test_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "module" then return Util.Beans.Objects.To_Object (From.Module.Get_Name); elsif Name = "name" then return From.Name; elsif Name = "email" then return From.Email; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "name" then From.Name := Value; elsif Name = "email" then From.Email := Value; end if; end Set_Value; function Create_Form_Bean (Plugin : in Test_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Test_Bean_Access := new Test_Bean; begin Result.Module := Plugin; return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin Log.Info ("Creating application"); T.App := new AWA.Applications.Application; C.Copy (Util.Tests.Get_Properties); C.Set ("app_search_dirs", Util.Tests.Get_Path ("regtests") & ";" & C.Get ("app_search_dirs", "")); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Log.Info ("Releasing application"); Free (T.App); end Tear_Down; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Create_Module (T : in out Test) is M : aliased Test_Module; R : aliased Module_Registry; Ctx : AWA.Services.Contexts.Service_Context; begin Ctx.Set_Context (T.App, null); R.Config.Copy (Util.Tests.Get_Properties); M.App := T.App.all'Access; Register (R'Unchecked_Access, M.App, M'Unchecked_Access, "empty", "uri"); T.Assert_Equals ("empty", M.Get_Name, "Invalid module name"); T.Assert_Equals ("uri", M.Get_URI, "Invalid module uri"); T.Assert (Find_By_Name (R, "empty") = M'Unchecked_Access, "Find_By_Name failed"); T.Assert (Find_By_URI (R, "uri") = M'Unchecked_Access, "Find_By_URI failed"); end Test_Create_Module; -- ------------------------------ -- Test looking for module -- ------------------------------ procedure Test_Find_Module (T : in out Test) is M : aliased Test_Module; Ctx : AWA.Services.Contexts.Service_Context; begin Ctx.Set_Context (T.App, null); M.App := T.App.all'Access; T.App.Register (M'Unchecked_Access, "empty", "uri"); T.Assert (M.Find_Module ("empty") /= null, "Find_Module should not return a null value"); T.Assert (M.Find_Module ("toto") = null, "Find_Module should return null"); end Test_Find_Module; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Application_Module (T : in out Test) is use ASF.Beans; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is use type Util.Beans.Basic.Readonly_Bean_Access; Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); T.Assert_Equals ("test-module", Util.Beans.Objects.To_String (Bean.Get_Value ("module")), "Bean module name"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; M : aliased Test_Module; Ctx : AWA.Services.Contexts.Service_Context; begin Ctx.Set_Context (T.App, null); M.App := T.App.all'Access; Module_Register.Register (Plugin => M, Name => "ASF.Applications.Tests.Form_Bean", Handler => Create_Form_Bean'Access); T.App.Register (M'Unchecked_Access, "test-module", "uri"); T.Assert (M.Find_Module ("test-module") /= null, "Find_Module should not return a null value"); T.Assert (M.Find_Module ("toto") = null, "Find_Module should return null"); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Application_Module; -- ------------------------------ -- Test module and navigation rules -- ------------------------------ procedure Test_Module_Navigation (T : in out Test) is M : aliased Test_Module; Ctx : AWA.Services.Contexts.Service_Context; begin Ctx.Set_Context (T.App, null); M.App := T.App.all'Access; Module_Register.Register (Plugin => M, Name => "ASF.Applications.Tests.Form_Bean", Handler => Create_Form_Bean'Access); T.App.Register (M'Unchecked_Access, "test-navigations", "uri"); T.Assert (M.Find_Module ("test-navigations") /= null, "Find_Module should not return a null value"); end Test_Module_Navigation; end AWA.Modules.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ddd81c764b5ba41bbb2befe3d2db3869998acc78
regtests/util-events-timers-tests.ads
regtests/util-events-timers-tests.ads
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Events.Timers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test and Util.Events.Timers.Timer with record Count : Natural := 0; end record; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class); -- Test empty timers. procedure Test_Empty_Timer (T : in out Test); procedure Test_Timer_Event (T : in out Test); end Util.Events.Timers.Tests;
----------------------------------------------------------------------- -- util-events-timers-tests -- Unit tests for timers -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Events.Timers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test and Util.Events.Timers.Timer with record Count : Natural := 0; Repeat : Natural := 0; end record; overriding procedure Time_Handler (Sub : in out Test; Event : in out Timer_Ref'Class); -- Test empty timers. procedure Test_Empty_Timer (T : in out Test); procedure Test_Timer_Event (T : in out Test); -- Test repeating timers. procedure Test_Repeat_Timer (T : in out Test); end Util.Events.Timers.Tests;
Declare the Test_Repeat_Timer procedure
Declare the Test_Repeat_Timer procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a2d69e2ebfc752e887870d4df972b2ce2b32cf66
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 EL.Contexts.Default; 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; -- Dispatch the request to the API handler. overriding procedure Dispatch (Handler : in Static_Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out Output_Stream'Class) is begin Handler.Handler (Req, Reply, Stream); end Dispatch; -- Register the API definition in the servlet registry. procedure Register (Registry : in out ASF.Servlets.Servlet_Registry'Class; Definition : in Descriptor_Access) is use type ASF.Routes.Route_Type_Access; use type ASF.Servlets.Servlet_Access; Dispatcher : constant ASF.Servlets.Request_Dispatcher := Registry.Get_Request_Dispatcher (Definition.Pattern.all); Servlet : ASF.Servlets.Servlet_Access := ASF.Servlets.Get_Servlet (Dispatcher); 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} already used by another page", Definition.Pattern.all); D := ASF.Servlets.Rest.Create_Route (Servlet); Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access); else D := ASF.Routes.Servlets.Rest.API_Route_Type (R.all)'Access; end if; else D := ASF.Servlets.Rest.Create_Route (Servlet); Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access); end if; if D.Descriptors (Definition.Method) /= null then Log.Error ("Route API for {0} is already used", Definition.Pattern.all); end if; D.Descriptors (Definition.Method) := Definition; end Insert; Ctx : EL.Contexts.Default.Default_Context; begin if Servlet = null then Log.Error ("Cannot register REST operation {0}: no REST servlet", Definition.Pattern.all); return; end if; Registry.Add_Route (Definition.Pattern.all, Ctx, Insert'Access); end Register; end ASF.Rest;
----------------------------------------------------------------------- -- asf-rest -- REST Support -- Copyright (C) 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 ASF.Routes; with ASF.Routes.Servlets.Rest; with ASF.Servlets.Rest; with EL.Contexts.Default; 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; -- Dispatch the request to the API handler. overriding procedure Dispatch (Handler : in Static_Descriptor; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class; Stream : in out Output_Stream'Class) is begin Handler.Handler (Req, Reply, Stream); end Dispatch; -- Register the API definition in the servlet registry. procedure Register (Registry : in out ASF.Servlets.Servlet_Registry'Class; Definition : in Descriptor_Access) is use type ASF.Routes.Route_Type_Access; use type ASF.Servlets.Servlet_Access; Dispatcher : constant ASF.Servlets.Request_Dispatcher := Registry.Get_Request_Dispatcher (Definition.Pattern.all); Servlet : constant ASF.Servlets.Servlet_Access := ASF.Servlets.Get_Servlet (Dispatcher); 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} already used by another page", Definition.Pattern.all); D := ASF.Servlets.Rest.Create_Route (Servlet); Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access); else D := ASF.Routes.Servlets.Rest.API_Route_Type (R.all)'Access; end if; else D := ASF.Servlets.Rest.Create_Route (Servlet); Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access); end if; if D.Descriptors (Definition.Method) /= null then Log.Error ("Route API for {0} is already used", Definition.Pattern.all); end if; D.Descriptors (Definition.Method) := Definition; end Insert; Ctx : EL.Contexts.Default.Default_Context; begin if Servlet = null then Log.Error ("Cannot register REST operation {0}: no REST servlet", Definition.Pattern.all); return; end if; Registry.Add_Route (Definition.Pattern.all, Ctx, Insert'Access); end Register; end ASF.Rest;
Change Servlet local variable to a constant
Change Servlet local variable to a constant
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
b411ba01e1df2ddfe24cb668a228e475633e7704
asfunit/asf-tests.adb
asfunit/asf-tests.adb
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Servlet.Core; with ASF.Servlets.Faces; with ASF.Servlets.Ajax; with Servlet.Filters; with Servlet.Core.Files; with Servlet.Core.Measures; with ASF.Responses; with ASF.Contexts.Faces; with EL.Variables.Default; package body ASF.Tests is use Util.Tests; CONTEXT_PATH : constant String := "/asfunit"; App_Created : ASF.Applications.Main.Application_Access; App : ASF.Applications.Main.Application_Access; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased Servlet.Core.Files.File_Servlet; Measures : aliased Servlet.Core.Measures.Measure_Servlet; -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; Empty : Util.Properties.Manager; begin if Application /= null then App := Application; else if App_Created = null then App_Created := new ASF.Applications.Main.Application; end if; App := App_Created; end if; C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "measures", Filter => Servlet.Filters.Filter'Class (Measures)'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.txt"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "files", Pattern => "*.jpg"); App.Add_Mapping (Name => "files", Pattern => "*.gif"); App.Add_Mapping (Name => "files", Pattern => "*.pdf"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); Servlet.Tests.Initialize (Empty, CONTEXT_PATH, App.all'Access); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is use type Servlet.Core.Servlet_Registry_Access; Result : constant Servlet.Core.Servlet_Registry_Access := Servlet.Tests.Get_Application; begin if Result = null then return App; elsif Result.all in ASF.Applications.Main.Application'Class then return ASF.Applications.Main.Application'Class (Result.all)'Access; else return App; end if; end Get_Application; -- ------------------------------ -- Cleanup the test instance. -- ------------------------------ overriding procedure Tear_Down (T : in out EL_Test) is procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class, EL.Contexts.Default.Default_Context_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class, EL.Variables.Variable_Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class, EL.Contexts.Default.Default_ELResolver_Access); begin ASF.Contexts.Faces.Restore (null); Free (T.ELContext); Free (T.Variables); Free (T.Root_Resolver); end Tear_Down; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out EL_Test) is begin T.ELContext := new EL.Contexts.Default.Default_Context; T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver; T.Variables := new EL.Variables.Default.Default_Variable_Mapper; T.ELContext.Set_Resolver (T.Root_Resolver.all'Access); T.ELContext.Set_Variable_Mapper (T.Variables.all'Access); end Set_Up; end ASF.Tests;
----------------------------------------------------------------------- -- asf-tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2013, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Servlet.Core; with ASF.Servlets.Faces; with ASF.Servlets.Ajax; with Servlet.Filters; with Servlet.Core.Files; with Servlet.Core.Measures; with ASF.Responses; with ASF.Contexts.Faces; with EL.Variables.Default; package body ASF.Tests is CONTEXT_PATH : constant String := "/asfunit"; App_Created : ASF.Applications.Main.Application_Access; App : ASF.Applications.Main.Application_Access; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased Servlet.Core.Files.File_Servlet; Measures : aliased Servlet.Core.Measures.Measure_Servlet; -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; Empty : Util.Properties.Manager; begin if Application /= null then App := Application; else if App_Created = null then App_Created := new ASF.Applications.Main.Application; end if; App := App_Created; end if; C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "measures", Filter => Servlet.Filters.Filter'Class (Measures)'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.txt"); App.Add_Mapping (Name => "files", Pattern => "*.png"); App.Add_Mapping (Name => "files", Pattern => "*.jpg"); App.Add_Mapping (Name => "files", Pattern => "*.gif"); App.Add_Mapping (Name => "files", Pattern => "*.pdf"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); Servlet.Tests.Initialize (Empty, CONTEXT_PATH, App.all'Access); end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is use type Servlet.Core.Servlet_Registry_Access; Result : constant Servlet.Core.Servlet_Registry_Access := Servlet.Tests.Get_Application; begin if Result = null then return App; elsif Result.all in ASF.Applications.Main.Application'Class then return ASF.Applications.Main.Application'Class (Result.all)'Access; else return App; end if; end Get_Application; -- ------------------------------ -- Cleanup the test instance. -- ------------------------------ overriding procedure Tear_Down (T : in out EL_Test) is procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class, EL.Contexts.Default.Default_Context_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class, EL.Variables.Variable_Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class, EL.Contexts.Default.Default_ELResolver_Access); begin ASF.Contexts.Faces.Restore (null); Free (T.ELContext); Free (T.Variables); Free (T.Root_Resolver); end Tear_Down; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out EL_Test) is begin T.ELContext := new EL.Contexts.Default.Default_Context; T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver; T.Variables := new EL.Variables.Default.Default_Variable_Mapper; T.ELContext.Set_Resolver (T.Root_Resolver.all'Access); T.ELContext.Set_Variable_Mapper (T.Variables.all'Access); end Set_Up; end ASF.Tests;
Remove unused use clause
Remove unused use clause
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7e6ab0883b69362872509f9087eaa95df4597305
src/asf-responses-mockup.adb
src/asf-responses-mockup.adb
----------------------------------------------------------------------- -- asf.responses -- ASF Requests -- Copyright (C) 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. ----------------------------------------------------------------------- -- The <b>ASF.Responses</b> package is an Ada implementation of -- the Java servlet response (JSR 315 5. The Response). package body ASF.Responses.Mockup is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin return Util.Strings.Maps.Has_Element (Pos); end Contains_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Resp.Headers.Iterate (Process => Process_Wrapper'Access); end Iterate_Headers; -- ------------------------------ -- Sets a response 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. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin Resp.Headers.Include (Name, Value); end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin if Resp.Headers.Contains (Name) then Resp.Headers.Include (Name, Resp.Headers.Element (Name) & ASCII.LF & Value); else Resp.Headers.Insert (Name, Value); end if; end Add_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 response. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Resp : in Response; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Resp.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; -- ------------------------------ -- Get the content written to the mockup output stream. -- ------------------------------ procedure Read_Content (Resp : in out Response; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Resp.Headers.Include ("Content-Type", Resp.Get_Content_Type); Resp.Content.Read (Into => Into); end Read_Content; -- ------------------------------ -- Clear the response content. -- This operation removes any content held in the output stream, clears the status, -- removes any header in the response. -- ------------------------------ procedure Clear (Resp : in out Response) is Content : Ada.Strings.Unbounded.Unbounded_String; begin Resp.Read_Content (Content); Resp.Status := SC_OK; Resp.Headers.Clear; end Clear; -- ------------------------------ -- Initialize the response mockup output stream. -- ------------------------------ overriding procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (128 * 1024); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; end ASF.Responses.Mockup;
----------------------------------------------------------------------- -- asf.responses -- ASF Requests -- Copyright (C) 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ASF.Responses</b> package is an Ada implementation of -- the Java servlet response (JSR 315 5. The Response). package body ASF.Responses.Mockup is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ function Contains_Header (Resp : in Response; Name : in String) return Boolean is Pos : constant Util.Strings.Maps.Cursor := Resp.Headers.Find (Name); begin return Util.Strings.Maps.Has_Element (Pos); end Contains_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ procedure Iterate_Headers (Resp : in Response; Process : not null access procedure (Name : in String; Value : in String)) is procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor); procedure Process_Wrapper (Position : in Util.Strings.Maps.Cursor) is begin Process.all (Name => Util.Strings.Maps.Key (Position), Value => Util.Strings.Maps.Element (Position)); end Process_Wrapper; begin Resp.Headers.Iterate (Process => Process_Wrapper'Access); end Iterate_Headers; -- ------------------------------ -- Sets a response 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. -- ------------------------------ procedure Set_Header (Resp : in out Response; Name : in String; Value : in String) is begin Resp.Headers.Include (Name, Value); end Set_Header; -- ------------------------------ -- Adds a response header with the given name and value. -- This method allows response headers to have multiple values. -- ------------------------------ procedure Add_Header (Resp : in out Response; Name : in String; Value : in String) is begin if Resp.Headers.Contains (Name) then Resp.Headers.Include (Name, Resp.Headers.Element (Name) & ASCII.LF & Value); else Resp.Headers.Insert (Name, Value); end if; end Add_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 response. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ function Get_Header (Resp : in Response; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Resp.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; -- ------------------------------ -- Get the content written to the mockup output stream. -- ------------------------------ procedure Read_Content (Resp : in out Response; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Resp.Headers.Include ("Content-Type", Resp.Get_Content_Type); Resp.Content.Flush (Into); end Read_Content; -- ------------------------------ -- Clear the response content. -- This operation removes any content held in the output stream, clears the status, -- removes any header in the response. -- ------------------------------ procedure Clear (Resp : in out Response) is Into : Ada.Strings.Unbounded.Unbounded_String; begin Resp.Content.Flush (Into); Resp.Status := SC_OK; Resp.Headers.Clear; end Clear; -- ------------------------------ -- Initialize the response mockup output stream. -- ------------------------------ overriding procedure Initialize (Resp : in out Response) is begin Resp.Content.Initialize (128 * 1024); Resp.Stream := Resp.Content'Unchecked_Access; end Initialize; end ASF.Responses.Mockup;
Update to use the Output_Buffer_Stream Flush operation to retrieve the output content
Update to use the Output_Buffer_Stream Flush operation to retrieve the output content
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
fb79c321a81b2bab1b0bd7e00bfca75ed121a99f
src/gen-commands-project.adb
src/gen-commands-project.adb
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Gen.Commands.Usage; return; end if; if Util.Strings.Index (Arg2, '@') > Arg2'First then Generator.Set_Project_Property ("author_email", Arg2); if Arg3'Length = 0 then Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2)); else Generator.Set_Project_Property ("author", Arg3); end if; elsif Util.Strings.Index (Arg3, '@') > Arg3'First then Generator.Set_Project_Property ("author", Arg2); Generator.Set_Project_Property ("author_email", Arg3); elsif Arg3'Length > 0 then Generator.Error ("The last argument should be the author's email address."); Gen.Commands.Usage; return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); end Help; end Gen.Commands.Project;
----------------------------------------------------------------------- -- gen-commands-project -- Project creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with GNAT.OS_Lib; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Project is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ function Get_Name_From_Email (Email : in String) return String; -- ------------------------------ -- Get the user name from the email address. -- Returns the possible user name from his email address. -- ------------------------------ function Get_Name_From_Email (Email : in String) return String is Pos : Natural := Util.Strings.Index (Email, '<'); begin if Pos > 0 then return Email (Email'First .. Pos - 1); end if; Pos := Util.Strings.Index (Email, '@'); if Pos > 0 then return Email (Email'First .. Pos - 1); else return Email; end if; end Get_Name_From_Email; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Name, Args); use GNAT.Command_Line; Web_Flag : aliased Boolean := False; Tool_Flag : aliased Boolean := False; Ado_Flag : aliased Boolean := False; Gtk_Flag : aliased Boolean := False; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l: ? -web -tool -ado -gtk") is when ASCII.NUL => exit; when '-' => if Full_Switch = "-web" then Web_Flag := True; elsif Full_Switch = "-tool" then Tool_Flag := True; elsif Full_Switch = "-ado" then Ado_Flag := True; elsif Full_Switch = "-gtk" then Gtk_Flag := True; end if; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "gpl3" then Generator.Set_Project_Property ("license", "gpl3"); elsif L = "mit" then Generator.Set_Project_Property ("license", "mit"); elsif L = "bsd3" then Generator.Set_Project_Property ("license", "bsd3"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary"); return; end if; end; when others => null; end case; end loop; if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then Web_Flag := True; end if; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; begin if Name'Length = 0 then Generator.Error ("Missing project name"); Cmd.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."); Cmd.Usage; return; end if; Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag)); Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag)); Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag)); Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag)); Generator.Set_Project_Name (Name); Generator.Set_Force_Save (False); if Ado_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado"); elsif Gtk_Flag then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk"); else Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project"); end if; Generator.Save_Project; declare use type GNAT.OS_Lib.String_Access; Path : constant GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf"); Args : GNAT.OS_Lib.Argument_List (1 .. 0); Status : Boolean; begin if Path = null then Generator.Error ("The 'autoconf' tool was not found. It is necessary to " & "generate the configure script."); Generator.Error ("Install 'autoconf' or launch it manually."); else Ada.Directories.Set_Directory (Generator.Get_Result_Directory); Log.Info ("Executing {0}", Path.all); GNAT.OS_Lib.Spawn (Path.all, Args, Status); if not Status then Generator.Error ("Execution of {0} failed", Path.all); end if; end if; end; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-project: Create a new Ada Web Application project"); Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]" & "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]"); New_Line; Put_Line (" Creates a new AWA application with the name passed in NAME."); Put_Line (" The application license is controlled with the -l option. "); Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses"); Put_Line (" license, the GNU licenses or a proprietary license."); Put_Line (" The author's name and email addresses are also reported in generated files."); New_Line; Put_Line (" --web Generate a Web application (the default)"); Put_Line (" --tool Generate a command line tool"); Put_Line (" --ado Generate a database tool operation for ADO"); Put_Line (" --gtk Generate a GtkAda project"); end Help; end Gen.Commands.Project;
Use the command usage procedure to report the program usage
Use the command usage procedure to report the program usage
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2eae1b566a884b04b271c4968df4ff86d76af394
src/gen-commands-templates.adb
src/gen-commands-templates.adb
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with GNAT.Command_Line; with Gen.Artifacts; with Util.Log.Loggers; with Util.Files; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; package body Gen.Commands.Templates is use Ada.Strings.Unbounded; use Util.Log; use GNAT.Command_Line; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Templates"); -- ------------------------------ -- Page Creation Command -- ------------------------------ -- This command adds a XHTML page to the web application. -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is function Get_Output_Dir return String; function Get_Output_Dir return String is Dir : constant String := Generator.Get_Result_Directory; begin if Length (Cmd.Base_Dir) = 0 then return Dir; else return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir)); end if; end Get_Output_Dir; Out_Dir : constant String := Get_Output_Dir; Iter : Param_Vectors.Cursor := Cmd.Params.First; begin Generator.Read_Project ("dynamo.xml", False); while Param_Vectors.Has_Element (Iter) loop declare P : constant Param := Param_Vectors.Element (Iter); Value : constant String := Get_Argument; begin if not P.Is_Optional and Value'Length = 0 then Generator.Error ("Missing argument for {0}", To_String (P.Argument)); return; end if; Generator.Set_Global (To_String (P.Name), Value); end; Param_Vectors.Next (Iter); end loop; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (To_Unbounded_String (Out_Dir)); declare Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First; begin while Util.Strings.Sets.Has_Element (Iter) loop Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, Util.Strings.Sets.Element (Iter)); Util.Strings.Sets.Next (Iter); end loop; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Generator); use Ada.Text_IO; begin Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title)); Put_Line ("Usage: " & To_String (Cmd.Usage)); New_Line; Put_Line (To_String (Cmd.Help_Msg)); end Help; type Command_Fields is (FIELD_NAME, FIELD_HELP, FIELD_USAGE, FIELD_TITLE, FIELD_BASEDIR, FIELD_PARAM, FIELD_PARAM_NAME, FIELD_PARAM_OPTIONAL, FIELD_PARAM_ARG, FIELD_TEMPLATE, FIELD_COMMAND); type Command_Loader is record Command : Command_Access := null; P : Param; end record; type Command_Loader_Access is access all Command_Loader; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object); function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String; -- ------------------------------ -- Convert the object value into a string and trim any space/tab/newlines. -- ------------------------------ function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is Result : constant String := Util.Beans.Objects.To_String (Value); First_Pos : Natural := Result'First; Last_Pos : Natural := Result'Last; C : Character; begin while First_Pos <= Last_Pos loop C := Result (First_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; First_Pos := First_Pos + 1; end loop; while Last_Pos >= First_Pos loop C := Result (Last_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; Last_Pos := Last_Pos - 1; end loop; return To_Unbounded_String (Result (First_Pos .. Last_Pos)); end To_String; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin if Field = FIELD_COMMAND then if Closure.Command /= null then Log.Info ("Adding command {0}", Closure.Command.Name); Add_Command (Name => To_String (Closure.Command.Name), Cmd => Closure.Command.all'Access); Closure.Command := null; end if; else if Closure.Command = null then Closure.Command := new Gen.Commands.Templates.Command; end if; case Field is when FIELD_NAME => Closure.Command.Name := To_String (Value); when FIELD_TITLE => Closure.Command.Title := To_String (Value); when FIELD_USAGE => Closure.Command.Usage := To_String (Value); when FIELD_HELP => Closure.Command.Help_Msg := To_String (Value); when FIELD_TEMPLATE => Closure.Command.Templates.Include (To_String (Value)); when FIELD_PARAM_NAME => Closure.P.Name := To_Unbounded_String (Value); when FIELD_PARAM_OPTIONAL => Closure.P.Is_Optional := To_Boolean (Value); when FIELD_PARAM_ARG => Closure.P.Argument := To_Unbounded_String (Value); when FIELD_PARAM => Closure.P.Value := To_Unbounded_String (Value); Closure.Command.Params.Append (Closure.P); Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Is_Optional := False; when FIELD_BASEDIR => Closure.Command.Base_Dir := To_Unbounded_String (Value); when FIELD_COMMAND => null; when others => null; end case; end if; end Set_Member; package Command_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader, Element_Type_Access => Command_Loader_Access, Fields => Command_Fields, Set_Member => Set_Member); Cmd_Mapper : aliased Command_Mapper.Mapper; -- ------------------------------ -- Read the template commands defined in dynamo configuration directory. -- ------------------------------ procedure Read_Commands (Generator : in out Gen.Generator.Handler) is procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Read the XML command file. -- ------------------------------ procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean) is pragma Unreferenced (Name); Loader : aliased Command_Loader; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading command file '{0}'", File_Path); Done := False; -- Create the mapping to load the XML command file. Reader.Add_Mapping ("commands", Cmd_Mapper'Access); -- Set the context for Set_Member. Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access); -- Read the XML command file. Reader.Parse (File_Path); exception when Ada.IO_Exceptions.Name_Error => Generator.Error ("Command file {0} does not exist", File_Path); end Read_Command; Config_Dir : constant String := Generator.Get_Config_Directory; Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir"); Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir); begin if Ada.Directories.Exists (Path) then Util.Files.Iterate_Files_Path (Path => Path, Pattern => "*.xml", Process => Read_Command'Access); end if; end Read_Commands; begin -- Setup the mapper to load XML commands. Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME); Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE); Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE); Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP); Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR); Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM); Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME); Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL); Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG); Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE); Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND); end Gen.Commands.Templates;
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with GNAT.Command_Line; with Gen.Artifacts; with Util.Log.Loggers; with Util.Files; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; package body Gen.Commands.Templates is use Ada.Strings.Unbounded; use Util.Log; use GNAT.Command_Line; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Templates"); -- ------------------------------ -- Page Creation Command -- ------------------------------ -- This command adds a XHTML page to the web application. -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is function Get_Output_Dir return String; function Get_Output_Dir return String is Dir : constant String := Generator.Get_Result_Directory; begin if Length (Cmd.Base_Dir) = 0 then return Dir; else return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir)); end if; end Get_Output_Dir; Out_Dir : constant String := Get_Output_Dir; Iter : Param_Vectors.Cursor := Cmd.Params.First; begin Generator.Read_Project ("dynamo.xml", False); while Param_Vectors.Has_Element (Iter) loop declare P : constant Param := Param_Vectors.Element (Iter); Value : constant String := Get_Argument; begin if not P.Is_Optional and Value'Length = 0 then Generator.Error ("Missing argument for {0}", To_String (P.Argument)); return; end if; Generator.Set_Global (To_String (P.Name), Value); end; Param_Vectors.Next (Iter); end loop; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (To_Unbounded_String (Out_Dir)); declare Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First; begin while Util.Strings.Sets.Has_Element (Iter) loop Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, Util.Strings.Sets.Element (Iter)); Util.Strings.Sets.Next (Iter); end loop; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Generator); use Ada.Text_IO; begin Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title)); Put_Line ("Usage: " & To_String (Cmd.Usage)); New_Line; Put_Line (To_String (Cmd.Help_Msg)); end Help; type Command_Fields is (FIELD_NAME, FIELD_HELP, FIELD_USAGE, FIELD_TITLE, FIELD_BASEDIR, FIELD_PARAM, FIELD_PARAM_NAME, FIELD_PARAM_OPTIONAL, FIELD_PARAM_ARG, FIELD_TEMPLATE, FIELD_COMMAND); type Command_Loader is record Command : Command_Access := null; P : Param; end record; type Command_Loader_Access is access all Command_Loader; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object); function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String; -- ------------------------------ -- Convert the object value into a string and trim any space/tab/newlines. -- ------------------------------ function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is Result : constant String := Util.Beans.Objects.To_String (Value); First_Pos : Natural := Result'First; Last_Pos : Natural := Result'Last; C : Character; begin while First_Pos <= Last_Pos loop C := Result (First_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; First_Pos := First_Pos + 1; end loop; while Last_Pos >= First_Pos loop C := Result (Last_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; Last_Pos := Last_Pos - 1; end loop; return To_Unbounded_String (Result (First_Pos .. Last_Pos)); end To_String; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin if Field = FIELD_COMMAND then if Closure.Command /= null then Log.Info ("Adding command {0}", Closure.Command.Name); Add_Command (Name => To_String (Closure.Command.Name), Cmd => Closure.Command.all'Access); Closure.Command := null; end if; else if Closure.Command = null then Closure.Command := new Gen.Commands.Templates.Command; end if; case Field is when FIELD_NAME => Closure.Command.Name := To_String (Value); when FIELD_TITLE => Closure.Command.Title := To_String (Value); when FIELD_USAGE => Closure.Command.Usage := To_String (Value); when FIELD_HELP => Closure.Command.Help_Msg := To_String (Value); when FIELD_TEMPLATE => Closure.Command.Templates.Include (To_String (Value)); when FIELD_PARAM_NAME => Closure.P.Name := To_Unbounded_String (Value); when FIELD_PARAM_OPTIONAL => Closure.P.Is_Optional := To_Boolean (Value); when FIELD_PARAM_ARG => Closure.P.Argument := To_Unbounded_String (Value); when FIELD_PARAM => Closure.P.Value := To_Unbounded_String (Value); Closure.Command.Params.Append (Closure.P); Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Is_Optional := False; when FIELD_BASEDIR => Closure.Command.Base_Dir := To_Unbounded_String (Value); when FIELD_COMMAND => null; end case; end if; end Set_Member; package Command_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader, Element_Type_Access => Command_Loader_Access, Fields => Command_Fields, Set_Member => Set_Member); Cmd_Mapper : aliased Command_Mapper.Mapper; -- ------------------------------ -- Read the template commands defined in dynamo configuration directory. -- ------------------------------ procedure Read_Commands (Generator : in out Gen.Generator.Handler) is procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Read the XML command file. -- ------------------------------ procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean) is pragma Unreferenced (Name); Loader : aliased Command_Loader; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading command file '{0}'", File_Path); Done := False; -- Create the mapping to load the XML command file. Reader.Add_Mapping ("commands", Cmd_Mapper'Access); -- Set the context for Set_Member. Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access); -- Read the XML command file. Reader.Parse (File_Path); exception when Ada.IO_Exceptions.Name_Error => Generator.Error ("Command file {0} does not exist", File_Path); end Read_Command; Config_Dir : constant String := Generator.Get_Config_Directory; Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir"); Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir); begin Log.Debug ("Checking commands in {0}", Path); if Ada.Directories.Exists (Path) then Util.Files.Iterate_Files_Path (Path => Path, Pattern => "*.xml", Process => Read_Command'Access); end if; end Read_Commands; begin -- Setup the mapper to load XML commands. Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME); Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE); Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE); Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP); Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR); Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM); Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME); Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL); Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG); Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE); Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND); end Gen.Commands.Templates;
Add a log and fix compilation warning
Add a log and fix compilation warning
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
8ef615fab24637363757516fc8f57e6e461cbcb1
src/ado-utils.adb
src/ado-utils.adb
----------------------------------------------------------------------- -- ado-utils -- Utility operations for ADO -- 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 ADO.Utils is -- ------------------------------ -- Build a bean object from the identifier. -- ------------------------------ function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is begin if Id = ADO.NO_IDENTIFIER then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); end if; end To_Object; -- ------------------------------ -- Build the identifier from the bean object. -- ------------------------------ function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is begin if Util.Beans.Objects.Is_Null (Value) then return ADO.NO_IDENTIFIER; else return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value)); end if; end To_Identifier; end ADO.Utils;
----------------------------------------------------------------------- -- ado-utils -- Utility operations for ADO -- 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 ADO.Utils is -- ------------------------------ -- Build a bean object from the identifier. -- ------------------------------ function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is begin if Id = ADO.NO_IDENTIFIER then return Util.Beans.Objects.Null_Object; else return Util.Beans.Objects.To_Object (Long_Long_Integer (Id)); end if; end To_Object; -- ------------------------------ -- Build the identifier from the bean object. -- ------------------------------ function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is begin if Util.Beans.Objects.Is_Null (Value) then return ADO.NO_IDENTIFIER; else return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value)); end if; end To_Identifier; -- ------------------------------ -- Compute the hash of the identifier. -- ------------------------------ function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type is use Ada.Containers; begin if Key < 0 then return Hash_Type (-Key); else return Hash_Type (Key); end if; end Hash; end ADO.Utils;
Implement the Hash operation
Implement the Hash operation
Ada
apache-2.0
stcarrez/ada-ado
6280a5e37856c4c0b73fe6a408860ab5878621ff
awa/src/awa-applications-configs.ads
awa/src/awa-applications-configs.ads
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Contexts.Default; with Util.Serialize.Mappers; -- The <b>AWA.Applications.Configs</b> package reads the application configuration files. package AWA.Applications.Configs is -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. generic Mapper : in out Util.Serialize.Mappers.Processing; App : in Application_Access; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean; package Reader_Config is end Reader_Config; -- Read the application configuration file and configure the application procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean); -- 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; end AWA.Applications.Configs;
----------------------------------------------------------------------- -- awa-applications-configs -- Read application configuration files -- Copyright (C) 2011, 2012, 2015, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Contexts.Default; with Util.Serialize.Mappers; with Keystore.Properties; -- The <b>AWA.Applications.Configs</b> package reads the application configuration files. package AWA.Applications.Configs is MAX_PREFIX_LENGTH : constant := 64; -- 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) with Pre => Prefix'Length <= MAX_PREFIX_LENGTH; -- XML reader configuration. By instantiating this generic package, the XML parser -- gets initialized to read the configuration for servlets, filters, managed beans, -- permissions, events and other configuration elements. generic Mapper : in out Util.Serialize.Mappers.Processing; App : in Application_Access; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean; package Reader_Config is end Reader_Config; -- Read the application configuration file and configure the application procedure Read_Configuration (App : in out Application'Class; File : in String; Context : in EL.Contexts.Default.Default_Context_Access; Override_Context : in Boolean); -- 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; end AWA.Applications.Configs;
Declare the Merge procedure to merge a standard configuration file with a secure configuration
Declare the Merge procedure to merge a standard configuration file with a secure configuration
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
3a2b4da561fc5a1fea73b40b10dedc4d895f3020
src/ado-caches.ads
src/ado-caches.ads
----------------------------------------------------------------------- -- ado-cache -- Simple cache management -- 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 Ada.Finalization; with ADO.Parameters; -- == Database Caches == -- The ADO cache manager allows to create and maintain cache of values and use the cache -- from the SQL expander to replace cached values before evaluating the SQL. The SQL expander -- identifies constructs as follows: -- -- $cache_name[entry-name] -- -- and look for the cache identified by <tt>cache_name</tt> and then replace the cache entry -- registered with the name <tt>entry-name</tt>. -- -- The cache manager is represented by the <tt>Cache_Manager</tt> type and the database -- session contains one cache manager. Applications may use their own cache in that case -- they will declare their cache as follows: -- -- M : ADO.Caches.Cache_Manager; -- -- A cache group is identified by a unique name and is represented by the <tt>Cache_Type</tt> -- base class. The cache group instance is registered in the cache manager by using the -- <tt>Add_Cache</tt> operation. package ADO.Caches is No_Value : exception; type Cache_Type is abstract limited new Ada.Finalization.Limited_Controlled with private; type Cache_Type_Access is access all Cache_Type'Class; -- 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. function Expand (Instance : in out Cache_Type; Name : in String) return ADO.Parameters.Parameter is abstract; type Cache_Manager is limited new Ada.Finalization.Limited_Controlled and ADO.Parameters.Expander with private; type Cache_Manager_Access is access all Cache_Manager'Class; -- Expand the name from the given group into a target parameter value to be used in -- the SQL query. The expander can look in a cache or in some configuration to find -- the value associated with the name and return it. 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 Cache_Manager; Group : in String; Name : in String) return ADO.Parameters.Parameter; -- Insert a new cache in the manager. The cache is identified by the given name. procedure Add_Cache (Manager : in out Cache_Manager; Name : in String; Cache : in Cache_Type_Access); -- Finalize the cache manager releasing every cache group. overriding procedure Finalize (Manager : in out Cache_Manager); private type Cache_Type is abstract limited new Ada.Finalization.Limited_Controlled with record Next : Cache_Type_Access; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type Cache_Manager is limited new Ada.Finalization.Limited_Controlled and ADO.Parameters.Expander with record First : Cache_Type_Access; end record; end ADO.Caches;
----------------------------------------------------------------------- -- ado-cache -- Simple cache management -- 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 Ada.Finalization; with ADO.Parameters; with Util.Log.Loggers; -- == Database Caches == -- The ADO cache manager allows to create and maintain cache of values and use the cache -- from the SQL expander to replace cached values before evaluating the SQL. The SQL expander -- identifies constructs as follows: -- -- $cache_name[entry-name] -- -- and look for the cache identified by <tt>cache_name</tt> and then replace the cache entry -- registered with the name <tt>entry-name</tt>. -- -- The cache manager is represented by the <tt>Cache_Manager</tt> type and the database -- session contains one cache manager. Applications may use their own cache in that case -- they will declare their cache as follows: -- -- M : ADO.Caches.Cache_Manager; -- -- A cache group is identified by a unique name and is represented by the <tt>Cache_Type</tt> -- base class. The cache group instance is registered in the cache manager by using the -- <tt>Add_Cache</tt> operation. package ADO.Caches is No_Value : exception; type Cache_Type is abstract limited new Ada.Finalization.Limited_Controlled with private; type Cache_Type_Access is access all Cache_Type'Class; -- 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. function Expand (Instance : in out Cache_Type; Name : in String) return ADO.Parameters.Parameter is abstract; type Cache_Manager is limited new Ada.Finalization.Limited_Controlled and ADO.Parameters.Expander with private; type Cache_Manager_Access is access all Cache_Manager'Class; -- Expand the name from the given group into a target parameter value to be used in -- the SQL query. The expander can look in a cache or in some configuration to find -- the value associated with the name and return it. 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 Cache_Manager; Group : in String; Name : in String) return ADO.Parameters.Parameter; -- Insert a new cache in the manager. The cache is identified by the given name. procedure Add_Cache (Manager : in out Cache_Manager; Name : in String; Cache : in Cache_Type_Access); -- Finalize the cache manager releasing every cache group. overriding procedure Finalize (Manager : in out Cache_Manager); private Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Caches"); type Cache_Type is abstract limited new Ada.Finalization.Limited_Controlled with record Next : Cache_Type_Access; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type Cache_Manager is limited new Ada.Finalization.Limited_Controlled and ADO.Parameters.Expander with record First : Cache_Type_Access; end record; end ADO.Caches;
Declare a logger instance
Declare a logger instance
Ada
apache-2.0
stcarrez/ada-ado
3cb5a6e6d629d2852e499d21b76dae090dc87279
awa/src/awa-users-modules.ads
awa/src/awa-users-modules.ads
----------------------------------------------------------------------- -- awa-users-module -- User management module -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with Security.Openid.Servlets; with AWA.Modules; with AWA.Users.Services; with AWA.Users.Filters; with AWA.Users.Servlets; -- == Introduction == -- The <b>Users.Module</b> manages the creation, update, removal and authentication of users -- in an application. The module provides the foundations for user management in -- a web application. -- -- A user can register himself by using a subscription form. In that case, a verification mail -- is sent and the user has to follow the verification link defined in the mail to finish -- the registration process. The user will authenticate using a password. -- -- A user can also use an OpenID account and be automatically registered. -- -- A user can have one or several permissions that allow to protect the application data. -- User permissions are managed by the <b>Permissions.Module</b>. -- -- == Configuration == -- The *users* module uses a set of configuration properties to configure the OpenID -- integration. -- -- @include awa-users-services.ads -- @include User.hbm.xml package AWA.Users.Modules is NAME : constant String := "users"; type User_Module is new AWA.Modules.Module with private; type User_Module_Access is access all User_Module'Class; -- Initialize the user module. overriding procedure Initialize (Plugin : in out User_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the user manager. function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Create a user manager. This operation can be overriden to provide another -- user service implementation. function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Get the user module instance associated with the current application. function Get_User_Module return User_Module_Access; -- Get the user manager instance associated with the current application. function Get_User_Manager return Services.User_Service_Access; private type User_Module is new AWA.Modules.Module with record Manager : Services.User_Service_Access := null; Key_Filter : aliased AWA.Users.Filters.Verify_Filter; Auth_Filter : aliased AWA.Users.Filters.Auth_Filter; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; end record; end AWA.Users.Modules;
----------------------------------------------------------------------- -- awa-users-module -- User management module -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with Security.Openid.Servlets; with AWA.Modules; with AWA.Users.Services; with AWA.Users.Filters; with AWA.Users.Servlets; -- == Introduction == -- The <b>Users.Module</b> manages the creation, update, removal and authentication of users -- in an application. The module provides the foundations for user management in -- a web application. -- -- A user can register himself by using a subscription form. In that case, a verification mail -- is sent and the user has to follow the verification link defined in the mail to finish -- the registration process. The user will authenticate using a password. -- -- A user can also use an OpenID account and be automatically registered. -- -- A user can have one or several permissions that allow to protect the application data. -- User permissions are managed by the <b>Permissions.Module</b>. -- -- == Configuration == -- The *users* module uses a set of configuration properties to configure the OpenID -- integration. -- -- @include awa-users-services.ads -- -- @include users.xml -- -- == Data Model == -- @include User.hbm.xml package AWA.Users.Modules is NAME : constant String := "users"; type User_Module is new AWA.Modules.Module with private; type User_Module_Access is access all User_Module'Class; -- Initialize the user module. overriding procedure Initialize (Plugin : in out User_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the user manager. function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Create a user manager. This operation can be overriden to provide another -- user service implementation. function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Get the user module instance associated with the current application. function Get_User_Module return User_Module_Access; -- Get the user manager instance associated with the current application. function Get_User_Manager return Services.User_Service_Access; private type User_Module is new AWA.Modules.Module with record Manager : Services.User_Service_Access := null; Key_Filter : aliased AWA.Users.Filters.Verify_Filter; Auth_Filter : aliased AWA.Users.Filters.Auth_Filter; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; end record; end AWA.Users.Modules;
Add the user module Ada beans in the documentation
Add the user module Ada beans in the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
68e63463364d0f35830068d8dcbc50a78f53306b
src/wiki-streams-text_io.ads
src/wiki-streams-text_io.ads
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016, 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 Ada.Wide_Wide_Text_IO; with Ada.Finalization; -- === Text_IO Input and Output streams === -- The `Wiki.Streams.Text_IO` package defines the `File_Input_Stream` and -- the `File_Output_Stream` types which use the `Ada.Wide_Wide_Text_IO` package -- to read or write the output streams. -- -- By default the `File_Input_Stream` is configured to read the standard input. -- The `Open` procedure can be used to read from a file knowing its name. -- -- The `File_Output_Stream` is configured to write on the standard output. -- The `Open` and `Create` procedure can be used to write on a file. -- package Wiki.Streams.Text_IO is type File_Input_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Input_Stream with private; type File_Input_Stream_Access is access all File_Input_Stream'Class; -- Open the file and prepare to read the input stream. procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := ""); -- Read the input stream and fill the `Into` buffer until either it is full or -- we reach the end of line. Returns in `Last` the last valid position in the -- `Into` buffer. When there is no character to read, return True in -- the `Eof` indicator. procedure Read (Input : in out File_Input_Stream; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean); -- Close the file. procedure Close (Stream : in out File_Input_Stream); -- Close the stream. overriding procedure Finalize (Stream : in out File_Input_Stream); type File_Output_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Output_Stream with private; type File_Output_Stream_Access is access all File_Output_Stream'Class; -- Open the file and prepare to write the output stream. procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := ""); -- Create the file and prepare to write the output stream. procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := ""); -- Close the file. procedure Close (Stream : in out File_Output_Stream); -- Write the string to the output stream. overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString); -- Write a single character to the output stream. overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar); -- Close the stream. overriding procedure Finalize (Stream : in out File_Output_Stream); private type File_Input_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Input_Stream with record File : Ada.Wide_Wide_Text_IO.File_Type; end record; type File_Output_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Output_Stream with record File : Ada.Wide_Wide_Text_IO.File_Type; Stdout : Boolean := True; end record; end Wiki.Streams.Text_IO;
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016, 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 Ada.Wide_Wide_Text_IO; with Ada.Finalization; -- === Text_IO Input and Output streams === -- The `Wiki.Streams.Text_IO` package defines the `File_Input_Stream` and -- the `File_Output_Stream` types which use the `Ada.Wide_Wide_Text_IO` package -- to read or write the output streams. -- -- By default the `File_Input_Stream` is configured to read the standard input. -- The `Open` procedure can be used to read from a file knowing its name. -- -- The `File_Output_Stream` is configured to write on the standard output. -- The `Open` and `Create` procedure can be used to write on a file. -- package Wiki.Streams.Text_IO is type File_Input_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Input_Stream with private; type File_Input_Stream_Access is access all File_Input_Stream'Class; -- Open the file and prepare to read the input stream. procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := ""); -- Read the input stream and fill the `Into` buffer until either it is full or -- we reach the end of line. Returns in `Last` the last valid position in the -- `Into` buffer. When there is no character to read, return True in -- the `Eof` indicator. procedure Read (Input : in out File_Input_Stream; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean); -- Close the file. procedure Close (Stream : in out File_Input_Stream); -- Close the stream. overriding procedure Finalize (Stream : in out File_Input_Stream); type File_Output_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Output_Stream with private; type File_Output_Stream_Access is access all File_Output_Stream'Class; -- Open the file and prepare to write the output stream. procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := ""); -- Create the file and prepare to write the output stream. procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := ""); -- Close the file. procedure Close (Stream : in out File_Output_Stream); -- Write the string to the output stream. overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString); -- Write a single character to the output stream. overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar); -- Close the stream. overriding procedure Finalize (Stream : in out File_Output_Stream); private type File_Input_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Input_Stream with record File : Ada.Wide_Wide_Text_IO.File_Type; Stdin : Boolean := True; end record; type File_Output_Stream is limited new Ada.Finalization.Limited_Controlled and Wiki.Streams.Output_Stream with record File : Ada.Wide_Wide_Text_IO.File_Type; Stdout : Boolean := True; end record; end Wiki.Streams.Text_IO;
Add Stdin boolean in File_Input_Stream to use the Ada Text_IO stdin file by default if Open is not called
Add Stdin boolean in File_Input_Stream to use the Ada Text_IO stdin file by default if Open is not called
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
dda8da9a6ba87dfe8cd033cae11ce81b7d4bb134
src/os-linux/util-systems-os.ads
src/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; -- 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 := '/'; 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 Integer := 4; FD_CLOEXEC : constant Integer := 1; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := 8#000#; O_WRONLY : constant Interfaces.C.int := 8#001#; O_RDWR : constant Interfaces.C.int := 8#002#; O_CREAT : constant Interfaces.C.int := 8#100#; O_EXCL : constant Interfaces.C.int := 8#200#; O_TRUNC : constant Interfaces.C.int := 8#1000#; O_APPEND : constant Interfaces.C.int := 8#2000#; 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 Integer; Flags : in Integer) 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"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; -- 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 := '/'; 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"); end Util.Systems.Os;
Use the Util.Systems.Constants generated package for some definitions
Use the Util.Systems.Constants generated package for some definitions
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e14b4ce3bed1ef16eebba85206b99ac6ace1c6eb
mat/src/mat-commands.ads
mat/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- The options that can be configured through the command line. type Options_Type is record Interactive : Boolean := True; Graphical : Boolean := False; Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class; Options : in out Options_Type); -- 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; end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- 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 Interactive : Boolean := True; Graphical : Boolean := False; Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class; Options : in out Options_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; -- Print the application usage. procedure Usage; end MAT.Commands;
Declare the Usage_Error exception
Declare the Usage_Error exception
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6bfa95a6f36d04e240a713d00f2a3a4d570931c7
src/util-beans-objects-time.adb
src/util-beans-objects-time.adb
----------------------------------------------------------------------- -- Util.Beans.Objects.Time -- Helper conversion for Ada Calendar Time -- Copyright (C) 2010, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces.C; with Ada.Calendar.Formatting; with Ada.Calendar.Conversions; package body Util.Beans.Objects.Time is use Ada.Calendar; Epoch : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Year_Number'First, Month => 1, Day => 1, Seconds => 12 * 3600.0); -- ------------------------------ -- Time Type -- ------------------------------ type Time_Type_Def is new Duration_Type_Def with null record; -- Get the type name function Get_Name (Type_Def : Time_Type_Def) return String; -- Convert the value into a string. function To_String (Type_Def : in Time_Type_Def; Value : in Object_Value) return String; Time_Type : aliased constant Time_Type_Def := Time_Type_Def '(others => <>); -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Time_Type_Def) return String is pragma Unreferenced (Type_Def); begin return "Time"; end Get_Name; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Time_Type_Def; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return Ada.Calendar.Formatting.Image (Epoch + Value.Time_Value); end To_String; -- ------------------------------ -- Create an object from the given value. -- ------------------------------ function To_Object (Value : in Ada.Calendar.Time) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_TIME, Time_Value => Value - Epoch), Type_Def => Time_Type'Access); end To_Object; -- ------------------------------ -- Convert the object into a time. -- Raises Constraint_Error if the object cannot be converter to the target type. -- ------------------------------ function To_Time (Value : in Object) return Ada.Calendar.Time is begin case Value.V.Of_Type is when TYPE_TIME => return Value.V.Time_Value + Epoch; when TYPE_STRING | TYPE_WIDE_STRING => declare T : constant String := Value.Type_Def.To_String (Value.V); begin return Ada.Calendar.Formatting.Value (T); exception -- Last chance, try to convert a Unix time displayed as an integer. when Constraint_Error => return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (T)); end; when others => raise Constraint_Error with "Conversion to a date is not possible"; end case; end To_Time; -- ------------------------------ -- Force the object to be a time. -- ------------------------------ function Cast_Time (Value : Object) return Object is begin case Value.V.Of_Type is when TYPE_TIME => return Value; when TYPE_STRING | TYPE_WIDE_STRING => return Time.To_Object (Formatting.Value (Value.Type_Def.To_String (Value.V))); when others => raise Constraint_Error with "Conversion to a date is not possible"; end case; end Cast_Time; end Util.Beans.Objects.Time;
----------------------------------------------------------------------- -- Util.Beans.Objects.Time -- Helper conversion for Ada Calendar Time -- Copyright (C) 2010, 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 Interfaces.C; with Ada.Calendar.Formatting; with Ada.Calendar.Conversions; package body Util.Beans.Objects.Time is use Ada.Calendar; Epoch : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Year_Number'First, Month => 1, Day => 1, Seconds => 12 * 3600.0); -- ------------------------------ -- Time Type -- ------------------------------ type Time_Type_Def is new Duration_Type_Def with null record; -- Get the type name function Get_Name (Type_Def : Time_Type_Def) return String; -- Convert the value into a string. function To_String (Type_Def : in Time_Type_Def; Value : in Object_Value) return String; Time_Type : aliased constant Time_Type_Def := Time_Type_Def '(null record); -- ------------------------------ -- Get the type name -- ------------------------------ function Get_Name (Type_Def : in Time_Type_Def) return String is pragma Unreferenced (Type_Def); begin return "Time"; end Get_Name; -- ------------------------------ -- Convert the value into a string. -- ------------------------------ function To_String (Type_Def : in Time_Type_Def; Value : in Object_Value) return String is pragma Unreferenced (Type_Def); begin return Ada.Calendar.Formatting.Image (Epoch + Value.Time_Value); end To_String; -- ------------------------------ -- Create an object from the given value. -- ------------------------------ function To_Object (Value : in Ada.Calendar.Time) return Object is begin return Object '(Controlled with V => Object_Value '(Of_Type => TYPE_TIME, Time_Value => Value - Epoch), Type_Def => Time_Type'Access); end To_Object; -- ------------------------------ -- Convert the object into a time. -- Raises Constraint_Error if the object cannot be converter to the target type. -- ------------------------------ function To_Time (Value : in Object) return Ada.Calendar.Time is begin case Value.V.Of_Type is when TYPE_TIME => return Value.V.Time_Value + Epoch; when TYPE_STRING | TYPE_WIDE_STRING => declare T : constant String := Value.Type_Def.To_String (Value.V); begin return Ada.Calendar.Formatting.Value (T); exception -- Last chance, try to convert a Unix time displayed as an integer. when Constraint_Error => return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (T)); end; when others => raise Constraint_Error with "Conversion to a date is not possible"; end case; end To_Time; -- ------------------------------ -- Force the object to be a time. -- ------------------------------ function Cast_Time (Value : Object) return Object is begin case Value.V.Of_Type is when TYPE_TIME => return Value; when TYPE_STRING | TYPE_WIDE_STRING => return Time.To_Object (Formatting.Value (Value.Type_Def.To_String (Value.V))); when others => raise Constraint_Error with "Conversion to a date is not possible"; end case; end Cast_Time; end Util.Beans.Objects.Time;
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
eb128b61bdae1e85b34fd1166f46c30a9998cf78
src/asf-contexts-flash.adb
src/asf-contexts-flash.adb
----------------------------------------------------------------------- -- contexts-facelets-flash -- Flash context -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Sessions; with ASF.Applications.Messages.Utils; package body ASF.Contexts.Flash is -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Flash : in out Flash_Context; Name : in String; Value : in Util.Beans.Objects.Object) is Instance : Flash_Bean_Access; begin Flash.Get_Execute_Flash (Instance); if Util.Beans.Objects.Is_Null (Value) then Instance.Attributes.Delete (Name); else Instance.Attributes.Include (Name, Value); end if; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Flash : in out Flash_Context; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object) is begin Flash.Set_Attribute (To_String (Name), Value); end Set_Attribute; -- ------------------------------ -- Get the attribute with the given name from the 'previous' flash context. -- ------------------------------ function Get_Attribute (Flash : in Flash_Context; Name : in String) return Util.Beans.Objects.Object is begin if Flash.Previous = null then return Util.Beans.Objects.Null_Object; else declare Pos : constant Util.Beans.Objects.Maps.Cursor := Flash.Previous.Attributes.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then return Util.Beans.Objects.Maps.Element (Pos); else return Util.Beans.Objects.Null_Object; end if; end; end if; end Get_Attribute; -- Keep in the flash context the request attribute identified by the name <b>Name</b>. procedure Keep (Flash : in out Flash_Context; Name : in String) is begin null; end Keep; -- ------------------------------ -- Returns True if the <b>Redirect</b> property was set on the previous flash instance. -- ------------------------------ function Is_Redirect (Flash : in Flash_Context) return Boolean is begin return Flash.Previous /= null and then Flash.Previous.Redirect; end Is_Redirect; -- Set this property to True to indicate to the next request on this session will be -- a redirect. After this call, the next request will return the <b>Redirect</b> value -- when the <b>Is_Redirect</b> function will be called. procedure Set_Redirect (Flash : in out Flash_Context; Redirect : in Boolean) is begin null; end Set_Redirect; -- ------------------------------ -- Returns True if the faces messages that are queued in the faces context must be -- preserved so they are accessible through the flash instance at the next request. -- ------------------------------ function Is_Keep_Messages (Flash : in Flash_Context) return Boolean is begin return Flash.Keep_Messages; end Is_Keep_Messages; -- ------------------------------ -- Set the keep messages property which controlls whether the faces messages -- that are queued in the faces context must be preserved so they are accessible through -- the flash instance at the next request. -- ------------------------------ procedure Set_Keep_Messages (Flash : in out Flash_Context; Value : in Boolean) is begin Flash.Keep_Messages := Value; end Set_Keep_Messages; -- ------------------------------ -- Perform any specific action before processing the phase referenced by <b>Phase</b>. -- This operation is used to restore the flash context for a new request. -- ------------------------------ procedure Do_Pre_Phase_Actions (Flash : in out Flash_Context; Phase : in ASF.Events.Phases.Phase_Type; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Events.Phases.Phase_Type; use type Util.Beans.Basic.Readonly_Bean_Access; begin -- Restore the flash bean instance from the session if there is one. if Phase = ASF.Events.Phases.RESTORE_VIEW then declare S : constant ASF.Sessions.Session := Context.Get_Session; B : access Util.Beans.Basic.Readonly_Bean'Class; begin if S.Is_Valid then Flash.Object := S.Get_Attribute ("asf.flash.bean"); B := Util.Beans.Objects.To_Bean (Flash.Object); if B /= null and then B.all in Flash_Bean'Class then Flash.Previous := Flash_Bean'Class (B.all)'Unchecked_Access; Context.Add_Messages ("", Flash.Previous.Messages); end if; end if; end; end if; end Do_Pre_Phase_Actions; -- ------------------------------ -- Perform any specific action after processing the phase referenced by <b>Phase</b>. -- This operation is used to save the flash context -- ------------------------------ procedure Do_Post_Phase_Actions (Flash : in out Flash_Context; Phase : in ASF.Events.Phases.Phase_Type; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Events.Phases.Phase_Type; begin if (Phase = ASF.Events.Phases.INVOKE_APPLICATION or Phase = ASF.Events.Phases.RENDER_RESPONSE) and then not Flash.Last_Phase_Done then Flash.Do_Last_Phase_Actions (Context); end if; end Do_Post_Phase_Actions; -- ------------------------------ -- Perform the last actions that must be made to save the flash context in the session. -- ------------------------------ procedure Do_Last_Phase_Actions (Flash : in out Flash_Context; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is S : ASF.Sessions.Session := Context.Get_Session; begin -- If we have to keep the messages, save them in the flash bean context if there are any. if Flash.Keep_Messages then declare Messages : constant Applications.Messages.Vectors.Cursor := Context.Get_Messages (""); begin if ASF.Applications.Messages.Vectors.Has_Element (Messages) then if Flash.Next = null then Flash.Next := new Flash_Bean; end if; ASF.Applications.Messages.Utils.Copy (Flash.Next.Messages, Messages); end if; end; end if; if S.Is_Valid then S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.Null_Object); elsif Flash.Next /= null then S := Context.Get_Session (Create => True); end if; if Flash.Next /= null then S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.To_Object (Flash.Next.all'Access)); end if; Flash.Last_Phase_Done := True; end Do_Last_Phase_Actions; procedure Get_Active_Flash (Flash : in out Flash_Context; Result : out Flash_Bean_Access) is begin if Flash.Previous = null then null; end if; Result := Flash.Previous; end Get_Active_Flash; procedure Get_Execute_Flash (Flash : in out Flash_Context; Result : out Flash_Bean_Access) is begin if Flash.Next = null then Flash.Next := new Flash_Bean; end if; Result := Flash.Next; end Get_Execute_Flash; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Flash_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; end ASF.Contexts.Flash;
----------------------------------------------------------------------- -- contexts-facelets-flash -- Flash context -- 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 ASF.Sessions; with ASF.Applications.Messages.Utils; package body ASF.Contexts.Flash is -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Flash : in out Flash_Context; Name : in String; Value : in Util.Beans.Objects.Object) is Instance : Flash_Bean_Access; begin Flash.Get_Execute_Flash (Instance); if Util.Beans.Objects.Is_Null (Value) then Instance.Attributes.Delete (Name); else Instance.Attributes.Include (Name, Value); end if; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Flash : in out Flash_Context; Name : in Unbounded_String; Value : in Util.Beans.Objects.Object) is begin Flash.Set_Attribute (To_String (Name), Value); end Set_Attribute; -- ------------------------------ -- Get the attribute with the given name from the 'previous' flash context. -- ------------------------------ function Get_Attribute (Flash : in Flash_Context; Name : in String) return Util.Beans.Objects.Object is begin if Flash.Previous = null then return Util.Beans.Objects.Null_Object; else declare Pos : constant Util.Beans.Objects.Maps.Cursor := Flash.Previous.Attributes.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then return Util.Beans.Objects.Maps.Element (Pos); else return Util.Beans.Objects.Null_Object; end if; end; end if; end Get_Attribute; -- Keep in the flash context the request attribute identified by the name <b>Name</b>. procedure Keep (Flash : in out Flash_Context; Name : in String) is begin null; end Keep; -- ------------------------------ -- Returns True if the <b>Redirect</b> property was set on the previous flash instance. -- ------------------------------ function Is_Redirect (Flash : in Flash_Context) return Boolean is begin return Flash.Previous /= null and then Flash.Previous.Redirect; end Is_Redirect; -- Set this property to True to indicate to the next request on this session will be -- a redirect. After this call, the next request will return the <b>Redirect</b> value -- when the <b>Is_Redirect</b> function will be called. procedure Set_Redirect (Flash : in out Flash_Context; Redirect : in Boolean) is begin null; end Set_Redirect; -- ------------------------------ -- Returns True if the faces messages that are queued in the faces context must be -- preserved so they are accessible through the flash instance at the next request. -- ------------------------------ function Is_Keep_Messages (Flash : in Flash_Context) return Boolean is begin return Flash.Keep_Messages; end Is_Keep_Messages; -- ------------------------------ -- Set the keep messages property which controlls whether the faces messages -- that are queued in the faces context must be preserved so they are accessible through -- the flash instance at the next request. -- ------------------------------ procedure Set_Keep_Messages (Flash : in out Flash_Context; Value : in Boolean) is begin Flash.Keep_Messages := Value; end Set_Keep_Messages; -- ------------------------------ -- Perform any specific action before processing the phase referenced by <b>Phase</b>. -- This operation is used to restore the flash context for a new request. -- ------------------------------ procedure Do_Pre_Phase_Actions (Flash : in out Flash_Context; Phase : in ASF.Events.Phases.Phase_Type; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Events.Phases.Phase_Type; use type Util.Beans.Basic.Readonly_Bean_Access; begin -- Restore the flash bean instance from the session if there is one. if Phase = ASF.Events.Phases.RESTORE_VIEW then declare S : constant ASF.Sessions.Session := Context.Get_Session; B : access Util.Beans.Basic.Readonly_Bean'Class; begin if S.Is_Valid then Flash.Object := S.Get_Attribute ("asf.flash.bean"); B := Util.Beans.Objects.To_Bean (Flash.Object); if B /= null and then B.all in Flash_Bean'Class then Flash.Previous := Flash_Bean'Class (B.all)'Unchecked_Access; Context.Add_Messages ("", Flash.Previous.Messages); end if; end if; end; end if; end Do_Pre_Phase_Actions; -- ------------------------------ -- Perform any specific action after processing the phase referenced by <b>Phase</b>. -- This operation is used to save the flash context -- ------------------------------ procedure Do_Post_Phase_Actions (Flash : in out Flash_Context; Phase : in ASF.Events.Phases.Phase_Type; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Events.Phases.Phase_Type; begin if (Phase = ASF.Events.Phases.INVOKE_APPLICATION or Phase = ASF.Events.Phases.RENDER_RESPONSE) and then not Flash.Last_Phase_Done then Flash.Do_Last_Phase_Actions (Context); end if; end Do_Post_Phase_Actions; -- ------------------------------ -- Perform the last actions that must be made to save the flash context in the session. -- ------------------------------ procedure Do_Last_Phase_Actions (Flash : in out Flash_Context; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is S : ASF.Sessions.Session := Context.Get_Session; begin -- If we have to keep the messages, save them in the flash bean context if there are any. if Flash.Keep_Messages then declare Messages : constant Applications.Messages.Vectors.Cursor := Context.Get_Messages (""); begin if ASF.Applications.Messages.Vectors.Has_Element (Messages) then if Flash.Next = null then Flash.Next := new Flash_Bean; end if; ASF.Applications.Messages.Utils.Copy (Flash.Next.Messages, Messages); end if; end; end if; if S.Is_Valid then S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.Null_Object); elsif Flash.Next /= null then S := Context.Get_Session (Create => True); end if; if Flash.Next /= null then S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.To_Object (Flash.Next.all'Access)); end if; Flash.Last_Phase_Done := True; end Do_Last_Phase_Actions; procedure Get_Active_Flash (Flash : in out Flash_Context; Result : out Flash_Bean_Access) is begin if Flash.Previous = null then null; end if; Result := Flash.Previous; end Get_Active_Flash; procedure Get_Execute_Flash (Flash : in out Flash_Context; Result : out Flash_Bean_Access) is begin if Flash.Next = null then Flash.Next := new Flash_Bean; end if; Result := Flash.Next; end Get_Execute_Flash; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. function Get_Value (From : in Flash_Bean; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (From, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; end ASF.Contexts.Flash;
Fix indentation style warning
Fix indentation style warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
da54e255a24e590786e45af4105335f9e62b5fb2
src/postgresql/ado-postgresql.ads
src/postgresql/ado-postgresql.ads
----------------------------------------------------------------------- -- 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 Util.Properties; -- === PostgreSQL Database Driver === -- The PostgreSQL database driver can be initialize explicitly by using the `ado_mysql` -- GNAT project and calling the initialization procedure. -- -- ADO.Postgresql.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "postgresql://localhost:5432/ado_test?user=ado&password=ado"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Postgresql.Initialize (Config); -- -- The PostgreSQL database driver supports the following properties: -- -- | Name | Description | -- | ----------- | --------- | -- | user | The user name to connect to the server | -- | password | The user password to connect to the server | -- package 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); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); 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 Util.Properties; -- === PostgreSQL Database Driver === -- The PostgreSQL database driver can be initialize explicitly by using the `ado_mysql` -- GNAT project and calling the initialization procedure. -- -- ADO.Postgresql.Initialize ("db.properties"); -- -- The set of configuration properties can be set programatically and passed to the -- `Initialize` operation. -- -- Config : Util.Properties.Manager; -- ... -- Config.Set ("ado.database", "postgresql://localhost:5432/ado_test?user=ado&password=ado"); -- Config.Set ("ado.queries.path", ".;db"); -- ADO.Postgresql.Initialize (Config); -- -- The PostgreSQL database driver supports the following properties: -- -- | Name | Description | -- | ----------- | --------- | -- | user | The user name to connect to the server | -- | password | The user password to connect to the server | -- package ADO.Postgresql is -- Initialize the Postgresql driver. procedure Initialize; -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. procedure Initialize (Config : in String); -- Initialize the drivers and the library and configure the runtime with the given properties. procedure Initialize (Config : in Util.Properties.Manager'Class); end ADO.Postgresql;
Declare the Initialize procedure
Declare the Initialize procedure
Ada
apache-2.0
stcarrez/ada-ado
c73fd6d023256a9296cb3584ff607ec223acd158
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; end MAT.Expressions;
Implement the Create_Time operation
Implement the Create_Time operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
7a63c73032afa8592da41a0a13bdb4ee061c8b5d
awa/src/awa-users-filters.adb
awa/src/awa-users-filters.adb
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- 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 Util.Log.Loggers; with ASF.Cookies; with AWA.Users.Services; with AWA.Users.Modules; package body AWA.Users.Filters is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Filters"); -- ------------------------------ -- Set the user principal on the session associated with the ASF request. -- ------------------------------ procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in Principals.Principal_Access) is Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Initialize the filter and configure the redirection URIs. -- ------------------------------ procedure Initialize (Filter : in out Auth_Filter; Context : in ASF.Servlets.Servlet_Registry'Class) is URI : constant String := Context.Get_Init_Parameter (AUTH_FILTER_REDIRECT_PARAM); begin Log.Info ("Using login URI: {0}", URI); if URI = "" then Log.Error ("The login URI is empty. Redirection to the login page will not work."); end if; Filter.Login_URI := To_Unbounded_String (URI); ASF.Security.Filters.Auth_Filter (Filter).Initialize (Context); end Initialize; procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access) is pragma Unreferenced (F, Session); use AWA.Users.Modules; use AWA.Users.Services; Manager : constant User_Service_Access := AWA.Users.Modules.Get_User_Manager; P : AWA.Users.Principals.Principal_Access; begin Manager.Authenticate (Cookie => Auth_Id, Ip_Addr => "", Principal => P); Principal := P.all'Access; -- Setup a new AID cookie with the new connection session. declare Cookie : constant String := Manager.Get_Authenticate_Cookie (P.Get_Session_Identifier); C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie); begin ASF.Cookies.Set_Path (C, Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 15 * 86400); Response.Add_Cookie (Cookie => C); end; exception when Not_Found => Principal := null; end Authenticate; -- ------------------------------ -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. -- ------------------------------ overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Login_URI : constant String := To_String (Filter.Login_URI); Context : constant String := Request.Get_Context_Path; Servlet : constant String := Request.Get_Servlet_Path; URL : constant String := Context & Servlet & Request.Get_Path_Info; C : ASF.Cookies.Cookie := ASF.Cookies.Create (REDIRECT_COOKIE, URL); begin Log.Info ("User is not logged, redirecting to {0}", Login_URI); ASF.Cookies.Set_Path (C, Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 86400); Response.Add_Cookie (Cookie => C); if Request.Get_Header ("X-Requested-With") = "" then Response.Send_Redirect (Location => Login_URI); else Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED); end if; end Do_Login; -- ------------------------------ -- Initialize the filter and configure the redirection URIs. -- ------------------------------ overriding procedure Initialize (Filter : in out Verify_Filter; Context : in ASF.Servlets.Servlet_Registry'Class) is URI : constant String := Context.Get_Init_Parameter (VERIFY_FILTER_REDIRECT_PARAM); begin Filter.Invalid_Key_URI := To_Unbounded_String (URI); end Initialize; -- ------------------------------ -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. -- ------------------------------ overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is Key : constant String := Request.Get_Parameter (PARAM_ACCESS_KEY); Manager : constant Users.Services.User_Service_Access := Users.Modules.Get_User_Manager; Principal : AWA.Users.Principals.Principal_Access; begin Log.Info ("Verify access key {0}", Key); Manager.Verify_User (Key => Key, IpAddr => "", Principal => Principal); Set_Session_Principal (Request, Principal); -- Request is authorized, proceed to the next filter. ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response); exception when AWA.Users.Services.Not_Found => declare URI : constant String := To_String (Filter.Invalid_Key_URI); begin Log.Info ("Invalid access key {0}, redirecting to {1}", Key, URI); Response.Send_Redirect (Location => URI); end; end Do_Filter; end AWA.Users.Filters;
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- 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 Util.Log.Loggers; with ASF.Cookies; with AWA.Users.Services; with AWA.Users.Modules; package body AWA.Users.Filters is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Filters"); -- ------------------------------ -- Set the user principal on the session associated with the ASF request. -- ------------------------------ procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in Principals.Principal_Access) is Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Initialize the filter and configure the redirection URIs. -- ------------------------------ procedure Initialize (Filter : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config) is URI : constant String := ASF.Servlets.Get_Init_Parameter (Config, AUTH_FILTER_REDIRECT_PARAM); begin Log.Info ("Using login URI: {0}", URI); if URI = "" then Log.Error ("The login URI is empty. Redirection to the login page will not work."); end if; Filter.Login_URI := To_Unbounded_String (URI); ASF.Security.Filters.Auth_Filter (Filter).Initialize (Config); end Initialize; procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access) is pragma Unreferenced (F, Session); use AWA.Users.Modules; use AWA.Users.Services; Manager : constant User_Service_Access := AWA.Users.Modules.Get_User_Manager; P : AWA.Users.Principals.Principal_Access; begin Manager.Authenticate (Cookie => Auth_Id, Ip_Addr => "", Principal => P); Principal := P.all'Access; -- Setup a new AID cookie with the new connection session. declare Cookie : constant String := Manager.Get_Authenticate_Cookie (P.Get_Session_Identifier); C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie); begin ASF.Cookies.Set_Path (C, Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 15 * 86400); Response.Add_Cookie (Cookie => C); end; exception when Not_Found => Principal := null; end Authenticate; -- ------------------------------ -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. -- ------------------------------ overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Login_URI : constant String := To_String (Filter.Login_URI); Context : constant String := Request.Get_Context_Path; Servlet : constant String := Request.Get_Servlet_Path; URL : constant String := Context & Servlet & Request.Get_Path_Info; C : ASF.Cookies.Cookie := ASF.Cookies.Create (REDIRECT_COOKIE, URL); begin Log.Info ("User is not logged, redirecting to {0}", Login_URI); ASF.Cookies.Set_Path (C, Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 86400); Response.Add_Cookie (Cookie => C); if Request.Get_Header ("X-Requested-With") = "" then Response.Send_Redirect (Location => Login_URI); else Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED); end if; end Do_Login; -- ------------------------------ -- Initialize the filter and configure the redirection URIs. -- ------------------------------ overriding procedure Initialize (Filter : in out Verify_Filter; Config : in ASF.Servlets.Filter_Config) is URI : constant String := ASF.Servlets.Get_Init_Parameter (Config, VERIFY_FILTER_REDIRECT_PARAM); begin Filter.Invalid_Key_URI := To_Unbounded_String (URI); end Initialize; -- ------------------------------ -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. -- ------------------------------ overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is Key : constant String := Request.Get_Parameter (PARAM_ACCESS_KEY); Manager : constant Users.Services.User_Service_Access := Users.Modules.Get_User_Manager; Principal : AWA.Users.Principals.Principal_Access; begin Log.Info ("Verify access key {0}", Key); Manager.Verify_User (Key => Key, IpAddr => "", Principal => Principal); Set_Session_Principal (Request, Principal); -- Request is authorized, proceed to the next filter. ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response); exception when AWA.Users.Services.Not_Found => declare URI : constant String := To_String (Filter.Invalid_Key_URI); begin Log.Info ("Invalid access key {0}, redirecting to {1}", Key, URI); Response.Send_Redirect (Location => URI); end; end Do_Filter; end AWA.Users.Filters;
Use the Filter_Config to get the filter URL configuration parameters
Use the Filter_Config to get the filter URL configuration parameters
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b1b8e1920df268e70a2bfa047da540dde9b66016
awa/plugins/awa-countries/tools/import_country.adb
awa/plugins/awa-countries/tools/import_country.adb
----------------------------------------------------------------------- -- import_country -- Read a Country csv file to update the database -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with ADO; with ADO.SQL; with ADO.Drivers; with ADO.Sessions; with ADO.Statements; with ADO.Sessions.Factory; with Util.Strings; with Util.Log.Loggers; with Util.Serialize.IO.CSV; with AWA.Countries.Models; procedure Import_Country is use Ada.Text_IO; use Util.Serialize.IO.CSV; use AWA.Countries.Models; use Ada.Containers; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Import_Country"); Country : AWA.Countries.Models.Country_Ref; DB : ADO.Sessions.Master_Session; package Country_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => AWA.Countries.Models.Country_Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); package Neighbors_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => String, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); Countries : Country_Map.Map; Neighbors : Neighbors_Map.Map; type CSV_Parser is new Util.Serialize.IO.CSV.Parser with null record; overriding procedure Set_Cell (Parser : in out CSV_Parser; Value : in String; Row : in Util.Serialize.IO.CSV.Row_Type; Column : in Util.Serialize.IO.CSV.Column_Type); overriding procedure Set_Cell (Parser : in out CSV_Parser; Value : in String; Row : in Util.Serialize.IO.CSV.Row_Type; Column : in Util.Serialize.IO.CSV.Column_Type) is pragma Unreferenced (Parser, Row); Query : ADO.SQL.Query; Found : Boolean; begin case Column is when 1 => -- The ISO code is unique, find the country Query.Bind_Param (1, Value); Query.Set_Filter ("iso_code = ?"); Country.Find (DB, Query, Found); if not Found then -- Build a new country object Country := AWA.Countries.Models.Null_Country; Country.Set_Iso_Code (Value); end if; Countries.Insert (Value, Country); when 2 => -- Ada.Text_IO.Put_Line ("ISO3: " & Value); null; when 3 => -- Ada.Text_IO.Put_Line ("ISON: " & Value); null; when 4 => -- Ada.Text_IO.Put_Line ("FIPS: " & Value); null; -- Country name when 5 => Country.Set_Name (Value); when 6 => -- Ada.Text_IO.Put_Line ("Capital: " & Value); null; when 7 | 8 => -- Area, Population null; -- Country continent when 9 => Country.Set_Continent (Value); -- Country TLD when 10 => Country.Set_Tld (Value); -- Country CurrencyCode when 11 => Country.Set_Currency_Code (Value); -- Country CurrencyName when 12 => Country.Set_Currency (Value); when 13 | 14 => -- Phone, postal code format null; when 15 => -- Ada.Text_IO.Put_Line ("Postal regex: " & Value); null; -- Country languages when 16 => Country.Set_Languages (Value); -- Country unique geonameid when 17 => if Value /= "" then Country.Set_Geonameid (Integer'Value (Value)); end if; when 18 => Country.Save (DB); Neighbors.Insert (Country.Get_Iso_Code, Value); when 19 => -- EquivalentFipsCode null; when others => null; end case; exception when E : others => Log.Error ("Column " & Util.Serialize.IO.CSV.Column_Type'Image (Column) & " value: " & Value, E, True); raise; end Set_Cell; procedure Build_Neighbors is Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Countries.Models.COUNTRY_NEIGHBOR_TABLE); Iter : Neighbors_Map.Cursor := Neighbors.First; Count : Natural := 0; begin Stmt.Execute; while Neighbors_Map.Has_Element (Iter) loop declare Name : constant String := Neighbors_Map.Key (Iter); List : constant String := Neighbors_Map.Element (Iter); Pos : Natural := List'First; N : Natural; begin Country := Countries.Element (Name); while Pos < List'Last loop N := Util.Strings.Index (List, ',', Pos); if N = 0 then N := List'Last; else N := N - 1; end if; if Pos < N and then Countries.Contains (List (Pos .. N)) then declare Neighbor : AWA.Countries.Models.Country_Neighbor_Ref; begin Neighbor.Set_Neighbor_Of (Country); Neighbor.Set_Neighbor (Countries.Element (List (Pos .. N))); Neighbor.Save (DB); Count := Count + 1; end; else Ada.Text_IO.Put_Line ("Country not found: " & List (Pos .. N)); end if; Pos := N + 2; end loop; end; Neighbors_Map.Next (Iter); end loop; Ada.Text_IO.Put_Line ("Created " & Natural'Image (Count) & " country neighbors"); end Build_Neighbors; Count : constant Natural := Ada.Command_Line.Argument_Count; Factory : ADO.Sessions.Factory.Session_Factory; Parser : CSV_Parser; begin Util.Log.Loggers.Initialize ("log4j.properties"); if Count /= 1 then Ada.Text_IO.Put_Line ("Usage: import_country file"); return; end if; -- Initialize the database drivers. ADO.Drivers.Initialize ("am.properties"); -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("ado.database")); DB := Factory.Get_Master_Session; DB.Begin_Transaction; declare File : constant String := Ada.Command_Line.Argument (1); begin Parser.Set_Comment_Separator ('#'); Parser.Set_Field_Separator (ASCII.HT); Parser.Parse (File); Ada.Text_IO.Put_Line ("Found " & Count_Type'Image (Countries.Length) & " countries"); Build_Neighbors; end; DB.Commit; end Import_Country;
----------------------------------------------------------------------- -- import_country -- Read a Country csv file to update the database -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Command_Line; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with ADO; with ADO.SQL; with ADO.Drivers; with ADO.Sessions; with ADO.Statements; with ADO.Sessions.Factory; with Util.Strings; with Util.Log.Loggers; with Util.Serialize.IO.CSV; with AWA.Countries.Models; procedure Import_Country is use Ada.Text_IO; use Util.Serialize.IO.CSV; use AWA.Countries.Models; use Ada.Containers; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Import_Country"); Country : AWA.Countries.Models.Country_Ref; DB : ADO.Sessions.Master_Session; package Country_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => AWA.Countries.Models.Country_Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); package Neighbors_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => String, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); Countries : Country_Map.Map; Neighbors : Neighbors_Map.Map; type CSV_Parser is new Util.Serialize.IO.CSV.Parser with null record; overriding procedure Set_Cell (Parser : in out CSV_Parser; Value : in String; Row : in Util.Serialize.IO.CSV.Row_Type; Column : in Util.Serialize.IO.CSV.Column_Type); overriding procedure Set_Cell (Parser : in out CSV_Parser; Value : in String; Row : in Util.Serialize.IO.CSV.Row_Type; Column : in Util.Serialize.IO.CSV.Column_Type) is pragma Unreferenced (Parser, Row); Query : ADO.SQL.Query; Found : Boolean; begin case Column is when 1 => -- The ISO code is unique, find the country Query.Bind_Param (1, Value); Query.Set_Filter ("iso_code = ?"); Country.Find (DB, Query, Found); if not Found then -- Build a new country object Country := AWA.Countries.Models.Null_Country; Country.Set_Iso_Code (Value); end if; Countries.Insert (Value, Country); when 2 => -- Ada.Text_IO.Put_Line ("ISO3: " & Value); null; when 3 => -- Ada.Text_IO.Put_Line ("ISON: " & Value); null; when 4 => -- Ada.Text_IO.Put_Line ("FIPS: " & Value); null; -- Country name when 5 => Country.Set_Name (Value); when 6 => -- Ada.Text_IO.Put_Line ("Capital: " & Value); null; when 7 | 8 => -- Area, Population null; -- Country continent when 9 => Country.Set_Continent (Value); -- Country TLD when 10 => Country.Set_Tld (Value); -- Country CurrencyCode when 11 => Country.Set_Currency_Code (Value); -- Country CurrencyName when 12 => Country.Set_Currency (Value); when 13 | 14 => -- Phone, postal code format null; when 15 => -- Ada.Text_IO.Put_Line ("Postal regex: " & Value); null; -- Country languages when 16 => Country.Set_Languages (Value); -- Country unique geonameid when 17 => if Value /= "" then Country.Set_Geonameid (Integer'Value (Value)); end if; when 18 => Country.Save (DB); Neighbors.Insert (Country.Get_Iso_Code, Value); when 19 => -- EquivalentFipsCode null; when others => null; end case; exception when E : others => Log.Error ("Column " & Util.Serialize.IO.CSV.Column_Type'Image (Column) & " value: " & Value, E, True); raise; end Set_Cell; procedure Build_Neighbors is Stmt : ADO.Statements.Delete_Statement := DB.Create_Statement (AWA.Countries.Models.COUNTRY_NEIGHBOR_TABLE); Iter : Neighbors_Map.Cursor := Neighbors.First; Count : Natural := 0; begin Stmt.Execute; while Neighbors_Map.Has_Element (Iter) loop declare Name : constant String := Neighbors_Map.Key (Iter); List : constant String := Neighbors_Map.Element (Iter); Pos : Natural := List'First; N : Natural; begin Country := Countries.Element (Name); while Pos < List'Last loop N := Util.Strings.Index (List, ',', Pos); if N = 0 then N := List'Last; else N := N - 1; end if; if Pos < N and then Countries.Contains (List (Pos .. N)) then declare Neighbor : AWA.Countries.Models.Country_Neighbor_Ref; begin Neighbor.Set_Neighbor_Of (Country); Neighbor.Set_Neighbor (Countries.Element (List (Pos .. N))); Neighbor.Save (DB); Count := Count + 1; end; else Ada.Text_IO.Put_Line ("Country not found: " & List (Pos .. N)); end if; Pos := N + 2; end loop; end; Neighbors_Map.Next (Iter); end loop; Ada.Text_IO.Put_Line ("Created " & Natural'Image (Count) & " country neighbors"); end Build_Neighbors; Count : constant Natural := Ada.Command_Line.Argument_Count; Factory : ADO.Sessions.Factory.Session_Factory; Parser : CSV_Parser; begin if Count /= 2 then Ada.Text_IO.Put_Line ("Usage: import_country config file"); return; end if; declare Config : constant String := Ada.Command_Line.Argument (1); begin Util.Log.Loggers.Initialize (Config); -- Initialize the database drivers. ADO.Drivers.Initialize (Config); -- Initialize the session factory to connect to the -- database defined by 'ado.database' property. Factory.Create (ADO.Drivers.Get_Config ("database")); end; DB := Factory.Get_Master_Session; DB.Begin_Transaction; declare File : constant String := Ada.Command_Line.Argument (2); begin Parser.Set_Comment_Separator ('#'); Parser.Set_Field_Separator (ASCII.HT); Parser.Parse (File); Ada.Text_IO.Put_Line ("Found " & Count_Type'Image (Countries.Length) & " countries"); Build_Neighbors; end; DB.Commit; end Import_Country;
Update the usage of the import tool
Update the usage of the import tool
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa
1389e872404f96da6800fd0ac838d3f8466e0973
testcases/stored_procs/stored_procs.adb
testcases/stored_procs/stored_procs.adb
with AdaBase; with Connect; with Ada.Text_IO; with AdaBase.Results.Sets; procedure Stored_Procs is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; stmt_acc : CON.Stmt_Type_access; procedure dump_result; procedure dump_result is function pad (S : String) return String; function pad (S : String) return String is field : String (1 .. 15) := (others => ' '); len : Natural := S'Length; begin field (1 .. len) := S; return field; end pad; row : ARS.Datarow; numcols : constant Natural := stmt_acc.column_count; begin for c in Natural range 1 .. numcols loop TIO.Put (pad (stmt_acc.column_name (c))); end loop; TIO.Put_Line (""); for c in Natural range 1 .. numcols loop TIO.Put ("============== "); end loop; TIO.Put_Line (""); loop row := stmt_acc.fetch_next; exit when row.data_exhausted; for c in Natural range 1 .. numcols loop TIO.Put (pad (row.column (c).as_string)); end loop; TIO.Put_Line (""); end loop; TIO.Put_Line (""); end dump_result; sql : constant String := "CALL multiple_rowsets"; set_fetched : Boolean; set_present : Boolean; begin CON.connect_database; declare stmt : aliased CON.Stmt_Type := CON.DR.call_stored_procedure ("multiple_rowsets", ""); begin if stmt.successful then set_fetched := True; else TIO.Put_Line ("Stored procedures not supported on " & CON.DR.trait_driver); end if; set_fetched := stmt.successful; stmt_acc := stmt'Unchecked_Access; loop if set_fetched then dump_result; end if; stmt.fetch_next_set (set_present, set_fetched); exit when not set_present; end loop; end; CON.DR.disconnect; end Stored_Procs;
with AdaBase; with Connect; with Ada.Text_IO; with AdaBase.Results.Sets; procedure Stored_Procs is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; stmt_acc : CON.Stmt_Type_access; procedure dump_result; procedure dump_result is function pad (S : String) return String; function pad (S : String) return String is field : String (1 .. 15) := (others => ' '); len : Natural := S'Length; begin field (1 .. len) := S; return field; end pad; row : ARS.Datarow; numcols : constant Natural := stmt_acc.column_count; begin for c in Natural range 1 .. numcols loop TIO.Put (pad (stmt_acc.column_name (c))); end loop; TIO.Put_Line (""); for c in Natural range 1 .. numcols loop TIO.Put ("============== "); end loop; TIO.Put_Line (""); loop row := stmt_acc.fetch_next; exit when row.data_exhausted; for c in Natural range 1 .. numcols loop TIO.Put (pad (row.column (c).as_string)); end loop; TIO.Put_Line (""); end loop; TIO.Put_Line (""); end dump_result; sql : constant String := "CALL multiple_rowsets"; set_fetched : Boolean; set_present : Boolean; begin CON.connect_database; declare stmt : aliased CON.Stmt_Type := CON.DR.call_stored_procedure ("multiple_rowsets", ""); begin set_fetched := stmt.successful; stmt_acc := stmt'Unchecked_Access; loop if set_fetched then dump_result; end if; stmt.fetch_next_set (set_present, set_fetched); exit when not set_present; end loop; end; CON.DR.disconnect; end Stored_Procs;
Remove obsolete sqlite case handling from stored procs test case
Remove obsolete sqlite case handling from stored procs test case
Ada
isc
jrmarino/AdaBase
43156fbb0363cec501b445fa918bd6eca3fbb827
src/util-concurrent-fifos.adb
src/util-concurrent-fifos.adb
----------------------------------------------------------------------- -- Util.Concurrent.Fifos -- Concurrent Fifo 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.Unchecked_Deallocation; package body Util.Concurrent.Fifos is -- ------------------------------ -- Put the element in the queue. -- ------------------------------ procedure Enqueue (Into : in out Fifo; Item : in Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then Into.Buffer.Enqueue (Item); else select Into.Buffer.Enqueue (Item); or delay Wait; raise Timeout; end select; end if; end Enqueue; -- ------------------------------ -- Get an element from the queue. -- Wait until one element gets available. -- ------------------------------ procedure Dequeue (From : in out Fifo; Item : out Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then From.Buffer.Dequeue (Item); else select From.Buffer.Dequeue (Item); or delay Wait; raise Timeout; end select; end if; end Dequeue; -- ------------------------------ -- Get the number of elements in the queue. -- ------------------------------ function Get_Count (From : in Fifo) return Natural is begin return From.Buffer.Get_Count; end Get_Count; -- ------------------------------ -- Set the queue size. -- ------------------------------ procedure Set_Size (Into : in out Fifo; Capacity : in Positive) is begin Into.Buffer.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Initializes the queue. -- ------------------------------ overriding procedure Initialize (Object : in out Fifo) is begin Object.Buffer.Set_Size (Default_Size); end Initialize; -- ------------------------------ -- Release the queue elements. -- ------------------------------ overriding procedure Finalize (Object : in out Fifo) is begin if Clear_On_Dequeue then while Object.Get_Count > 0 loop declare Unused : Element_Type; begin Object.Dequeue (Unused); end; end loop; end if; Object.Buffer.Set_Size (0); end Finalize; -- Queue of objects. protected body Protected_Fifo is -- ------------------------------ -- Put the element in the queue. -- If the queue is full, wait until some room is available. -- ------------------------------ entry Enqueue (Item : in Element_Type) when Count < Elements'Length is begin Elements (Last) := Item; Last := Last + 1; if Last > Elements'Last then Last := Elements'First; end if; Count := Count + 1; end Enqueue; -- ------------------------------ -- Get an element from the queue. -- Wait until one element gets available. -- ------------------------------ entry Dequeue (Item : out Element_Type) when Count > 0 is begin Count := Count - 1; Item := Elements (First); -- For the clear on dequeue mode, erase the queue element. -- If the element holds some storage or a reference, this gets cleared here. -- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue -- is false). There is no overhead when this is not used -- (ie, instantiation/compile time flag). if Clear_On_Dequeue then Elements (First) := Elements (0); end if; First := First + 1; if First > Elements'Last then First := Elements'First; end if; end Dequeue; -- ------------------------------ -- Get the number of elements in the queue. -- ------------------------------ function Get_Count return Natural is begin return Count; end Get_Count; -- ------------------------------ -- Set the queue size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); First_Pos : Natural := 1; begin if Clear_On_Dequeue then First_Pos := 0; end if; if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (First_Pos .. Capacity); else declare New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity); begin if Capacity > Elements'Length then New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last); else New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; end Protected_Fifo; end Util.Concurrent.Fifos;
----------------------------------------------------------------------- -- Util.Concurrent.Fifos -- Concurrent Fifo 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.Unchecked_Deallocation; package body Util.Concurrent.Fifos is -- ------------------------------ -- Put the element in the queue. -- ------------------------------ procedure Enqueue (Into : in out Fifo; Item : in Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then Into.Buffer.Enqueue (Item); else select Into.Buffer.Enqueue (Item); or delay Wait; raise Timeout; end select; end if; end Enqueue; -- ------------------------------ -- Get an element from the queue. -- Wait until one element gets available. -- ------------------------------ procedure Dequeue (From : in out Fifo; Item : out Element_Type; Wait : in Duration := FOREVER) is begin if Wait < 0.0 then From.Buffer.Dequeue (Item); else select From.Buffer.Dequeue (Item); or delay Wait; raise Timeout; end select; end if; end Dequeue; -- ------------------------------ -- Get the number of elements in the queue. -- ------------------------------ function Get_Count (From : in Fifo) return Natural is begin return From.Buffer.Get_Count; end Get_Count; -- ------------------------------ -- Set the queue size. -- ------------------------------ procedure Set_Size (Into : in out Fifo; Capacity : in Positive) is begin Into.Buffer.Set_Size (Capacity); end Set_Size; -- ------------------------------ -- Initializes the queue. -- ------------------------------ overriding procedure Initialize (Object : in out Fifo) is begin Object.Buffer.Set_Size (Default_Size); end Initialize; -- ------------------------------ -- Release the queue elements. -- ------------------------------ overriding procedure Finalize (Object : in out Fifo) is begin if Clear_On_Dequeue then while Object.Get_Count > 0 loop declare Unused : Element_Type; begin Object.Dequeue (Unused); end; end loop; end if; Object.Buffer.Set_Size (0); end Finalize; -- Queue of objects. protected body Protected_Fifo is -- ------------------------------ -- Put the element in the queue. -- If the queue is full, wait until some room is available. -- ------------------------------ entry Enqueue (Item : in Element_Type) when Count < Elements'Length is begin Elements (Last) := Item; Last := Last + 1; if Last > Elements'Last then if Clear_On_Dequeue then Last := Elements'First + 1; else Last := Elements'First; end if; end if; Count := Count + 1; end Enqueue; -- ------------------------------ -- Get an element from the queue. -- Wait until one element gets available. -- ------------------------------ entry Dequeue (Item : out Element_Type) when Count > 0 is begin Count := Count - 1; Item := Elements (First); -- For the clear on dequeue mode, erase the queue element. -- If the element holds some storage or a reference, this gets cleared here. -- The element used to clear is at index 0 (which does not exist if Clear_On_Dequeue -- is false). There is no overhead when this is not used -- (ie, instantiation/compile time flag). if Clear_On_Dequeue then Elements (First) := Elements (0); end if; First := First + 1; if First > Elements'Last then First := Elements'First; end if; end Dequeue; -- ------------------------------ -- Get the number of elements in the queue. -- ------------------------------ function Get_Count return Natural is begin return Count; end Get_Count; -- ------------------------------ -- Set the queue size. -- ------------------------------ procedure Set_Size (Capacity : in Natural) is procedure Free is new Ada.Unchecked_Deallocation (Element_Array, Element_Array_Access); First_Pos : Natural := 1; begin if Clear_On_Dequeue then First_Pos := 0; end if; if Capacity = 0 then Free (Elements); elsif Elements = null then Elements := new Element_Array (First_Pos .. Capacity); else declare New_Array : Element_Array_Access := new Element_Array (First_Pos .. Capacity); begin if Capacity > Elements'Length then New_Array (First_Pos .. Elements'Last) := Elements (First_Pos .. Elements'Last); else New_Array (First_Pos .. Capacity) := Elements (First_Pos .. Capacity); end if; Free (Elements); Elements := New_Array; end; end if; end Set_Size; end Protected_Fifo; end Util.Concurrent.Fifos;
Fix queue wrapping in the Clear_On_Dequeue instantiation mode
Fix queue wrapping in the Clear_On_Dequeue instantiation mode
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7ceda999ba3df5847c73d5934d7e46c6956d0c4a
matp/src/memory/mat-memory-targets.ads
matp/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- 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 MAT.Frames; with MAT.Events.Probes; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is Not_Found : exception; -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural := 0; Total_Alloc : MAT.Types.Target_Size := 0; Total_Free : MAT.Types.Target_Size := 0; Malloc_Count : Natural := 0; Free_Count : Natural := 0; Realloc_Count : Natural := 0; Used_Count : Natural := 0; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Find the region that matches the given name. function Find_Region (Memory : in Target_Memory; Name : in String) return Region_Info; -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Size : out MAT.Types.Target_Size; By : out MAT.Events.Event_Id_Type); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size; By : out MAT.Events.Event_Id_Type); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Region : in Region_Info); -- Find the region that matches the given name. function Find_Region (Name : in String) return Region_Info; -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Size : out MAT.Types.Target_Size; By : out MAT.Events.Event_Id_Type); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size; By : out MAT.Events.Event_Id_Type); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Regions : Region_Info_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- 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 MAT.Frames; with MAT.Events.Probes; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is Not_Found : exception; -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural := 0; Total_Alloc : MAT.Types.Target_Size := 0; Total_Free : MAT.Types.Target_Size := 0; Malloc_Count : Natural := 0; Free_Count : Natural := 0; Realloc_Count : Natural := 0; Used_Count : Natural := 0; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info); -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Find the region that matches the given name. function Find_Region (Memory : in Target_Memory; Name : in String) return Region_Info; -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Size : out MAT.Types.Target_Size; By : out MAT.Events.Event_Id_Type); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size; By : out MAT.Events.Event_Id_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Add the memory region from the list of memory region managed by the program. procedure Add_Region (Region : in Region_Info); -- Find the region that matches the given name. function Find_Region (Name : in String) return Region_Info; -- Find the memory region that intersect the given section described by <tt>From</tt> -- and <tt>To</tt>. Each memory region that intersects is added to the <tt>Into</tt> -- map. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Region_Info_Map); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Size : out MAT.Types.Target_Size; By : out MAT.Events.Event_Id_Type); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation; Old_Size : out MAT.Types.Target_Size; By : out MAT.Events.Event_Id_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Regions : Region_Info_Map; Stats : Memory_Stat; end Memory_Allocator; type Target_Memory is tagged limited record Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Remove the Create_Frame procedures
Remove the Create_Frame procedures
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
58ef02ee1feed09d4ec55302aa7526b887cd1622
src/asf-beans.adb
src/asf-beans.adb
----------------------------------------------------------------------- -- asf.beans -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body ASF.Beans is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Beans"); -- ------------------------------ -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access) is begin Log.Info ("Register bean class {0}", Name); Factory.Registry.Include (Name, Class_Binding_Ref.Create (Class)); end Register_Class; -- ------------------------------ -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Handler : in Create_Bean_Access) is Class : constant Default_Class_Binding_Access := new Default_Class_Binding; begin Class.Create := Handler; Register_Class (Factory, Name, Class.all'Access); end Register_Class; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is begin Log.Info ("Register bean '{0}' created by '{1}' in scope {2}", Name, Class, Scope_Type'Image (Scope)); declare Pos : constant Registry_Maps.Cursor := Factory.Registry.Find (Class); Binding : Bean_Binding; begin if not Registry_Maps.Has_Element (Pos) then Log.Error ("Class '{0}' does not exist. Cannot register bean '{1}'", Class, Name); return; end if; Binding.Create := Registry_Maps.Element (Pos); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end; end Register; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is Binding : Bean_Binding; begin Log.Info ("Register bean '{0}' in scope {2}", Name, Scope_Type'Image (Scope)); Binding.Create := Class_Binding_Ref.Create (Class); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end Register; -- ------------------------------ -- Register all the definitions from a factory to a main factory. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory) is begin declare Pos : Registry_Maps.Cursor := From.Registry.First; begin while Registry_Maps.Has_Element (Pos) loop Factory.Registry.Include (Key => Registry_Maps.Key (Pos), New_Item => Registry_Maps.Element (Pos)); Registry_Maps.Next (Pos); end loop; end; declare Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map); begin while Bean_Maps.Has_Element (Pos) loop Factory.Map.Include (Key => Bean_Maps.Key (Pos), New_Item => Bean_Maps.Element (Pos)); Bean_Maps.Next (Pos); end loop; end; end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type) is use type Util.Beans.Basic.Readonly_Bean_Access; Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare Binding : constant Bean_Binding := Bean_Maps.Element (Pos); begin Binding.Create.Value.Create (Name, Result); if Result /= null and then not Binding.Params.Is_Null then if Result.all in Util.Beans.Basic.Bean'Class then EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Result.all), Binding.Params.Value.Params, Context); else Log.Warn ("Bean {0} cannot be set with pre-defined properties as it does " & "not implement the Bean interface", To_String (Name)); end if; end if; Scope := Binding.Scope; end; else Result := null; Scope := ANY_SCOPE; end if; end Create; -- ------------------------------ -- Create a bean by using the registered create function. -- ------------------------------ procedure Create (Factory : in Default_Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); begin Result := Factory.Create.all; end Create; end ASF.Beans;
----------------------------------------------------------------------- -- asf.beans -- Bean Registration and Factory -- 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 Util.Log.Loggers; with Util.Beans.Objects.Maps; package body ASF.Beans is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Beans"); -- ------------------------------ -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access) is begin Log.Info ("Register bean class {0}", Name); Factory.Registry.Include (Name, Class_Binding_Ref.Create (Class)); end Register_Class; -- ------------------------------ -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Handler : in Create_Bean_Access) is Class : constant Default_Class_Binding_Access := new Default_Class_Binding; begin Class.Create := Handler; Register_Class (Factory, Name, Class.all'Access); end Register_Class; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is begin Log.Info ("Register bean '{0}' created by '{1}' in scope {2}", Name, Class, Scope_Type'Image (Scope)); declare Pos : constant Registry_Maps.Cursor := Factory.Registry.Find (Class); Binding : Bean_Binding; begin if not Registry_Maps.Has_Element (Pos) then Log.Error ("Class '{0}' does not exist. Cannot register bean '{1}'", Class, Name); return; end if; Binding.Create := Registry_Maps.Element (Pos); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end; end Register; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is Binding : Bean_Binding; begin Log.Info ("Register bean '{0}' in scope {2}", Name, Scope_Type'Image (Scope)); Binding.Create := Class_Binding_Ref.Create (Class); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end Register; -- ------------------------------ -- Register all the definitions from a factory to a main factory. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory) is begin declare Pos : Registry_Maps.Cursor := From.Registry.First; begin while Registry_Maps.Has_Element (Pos) loop Factory.Registry.Include (Key => Registry_Maps.Key (Pos), New_Item => Registry_Maps.Element (Pos)); Registry_Maps.Next (Pos); end loop; end; declare Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map); begin while Bean_Maps.Has_Element (Pos) loop Factory.Map.Include (Key => Bean_Maps.Key (Pos), New_Item => Bean_Maps.Element (Pos)); Bean_Maps.Next (Pos); end loop; end; end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type) is use type Util.Beans.Basic.Readonly_Bean_Access; Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare Binding : constant Bean_Binding := Bean_Maps.Element (Pos); begin Binding.Create.Value.Create (Name, Result); if Result /= null and then not Binding.Params.Is_Null then if Result.all in Util.Beans.Basic.Bean'Class then EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Result.all), Binding.Params.Value.Params, Context); else Log.Warn ("Bean {0} cannot be set with pre-defined properties as it does " & "not implement the Bean interface", To_String (Name)); end if; end if; Scope := Binding.Scope; end; else Result := null; Scope := ANY_SCOPE; end if; end Create; -- ------------------------------ -- Create a bean by using the registered create function. -- ------------------------------ procedure Create (Factory : in Default_Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); begin Result := Factory.Create.all; end Create; -- ------------------------------ -- Create a map bean object that allows to associate name/value pairs in a bean. -- ------------------------------ function Create_Map_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Util.Beans.Objects.Maps.Map_Bean; end Create_Map_Bean; end ASF.Beans;
Implement Create_Map_Bean function to build a Map_Bean object
Implement Create_Map_Bean function to build a Map_Bean object
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6928edbac3136b0c7f652a16f13c125c77849b17
awa/src/awa-permissions-services.ads
awa/src/awa-permissions-services.ads
----------------------------------------------------------------------- -- 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 AWA.Applications; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Permissions; with Security.Contexts; package AWA.Permissions.Services is type Permission_Manager is new Security.Permissions.Permission_Manager with private; type Permission_Manager_Access is access all Permission_Manager'Class; -- Get the permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access; -- Get the application instance. function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access; -- Set the application instance. procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access); -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b>. procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Read the policy file overriding procedure Read_Policy (Manager : in out Permission_Manager; File : in String); -- 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); -- 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); -- Create a permission manager for the given application. function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Permissions.Permission_Manager_Access; private type Permission_Manager is new Security.Permissions.Permission_Manager with record App : AWA.Applications.Application_Access := null; end record; 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 AWA.Applications; with ADO; with ADO.Sessions; with ADO.Objects; with Security.Policies; with Security.Contexts; package AWA.Permissions.Services is type Permission_Manager is new Security.Policies.Policy_Manager with private; type Permission_Manager_Access is access all Permission_Manager'Class; -- Get the permission manager associated with the security context. -- Returns null if there is none. function Get_Permission_Manager (Context : in Security.Contexts.Security_Context'Class) return Permission_Manager_Access; -- Get the application instance. function Get_Application (Manager : in Permission_Manager) return AWA.Applications.Application_Access; -- Set the application instance. procedure Set_Application (Manager : in out Permission_Manager; App : in AWA.Applications.Application_Access); -- Add a permission for the current user to access the entity identified by -- <b>Entity</b> and <b>Kind</b>. procedure Add_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Check that the current user has the specified permission. -- Raise NO_PERMISSION exception if the user does not have the permission. procedure Check_Permission (Manager : in Permission_Manager; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Permission : in Permission_Type); -- Read the policy file overriding procedure Read_Policy (Manager : in out Permission_Manager; File : in String); -- 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); -- 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); -- Create a permission manager for the given application. function Create_Permission_Manager (App : in AWA.Applications.Application_Access) return Security.Policies.Policy_Manager_Access; private type Permission_Manager is new Security.Policies.Policy_Manager with record App : AWA.Applications.Application_Access := null; end record; end AWA.Permissions.Services;
Use the Security.Policies package
Use the Security.Policies package
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
049069233bbb91202317ea4fedb236c4b2e137d4
mat/src/memory/mat-memory-tools.adb
mat/src/memory/mat-memory-tools.adb
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Memory.Tools is -- ------------------------------ -- Collect the information about memory slot sizes for the memory slots in the map. -- ------------------------------ procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is Iter : MAT.Memory.Allocation_Cursor := Memory.Ceiling (From); Pos : MAT.Memory.Allocation_Cursor; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; begin -- If there was no slot with the ceiling From address, we have to start from the last -- node because the memory slot may intersect our region. if not Allocation_Maps.Has_Element (Iter) then Iter := Memory.Last; if not Allocation_Maps.Has_Element (Iter) then return; end if; Addr := Allocation_Maps.Key (Iter); Size := Allocation_Maps.Element (Iter).Size; if Addr + Size < From then return; end if; end if; -- Move backward until the previous memory slot does not overlap anymore our region. -- In theory, going backward once is enough but if there was a target malloc issue, -- several malloc may overlap the same region (which is bad for the target). loop Pos := Allocation_Maps.Previous (Iter); exit when not Allocation_Maps.Has_Element (Pos); Addr := Allocation_Maps.Key (Pos); Size := Allocation_Maps.Element (Pos).Size; exit when Addr + Size < From; Iter := Pos; end loop; -- Add the memory slots until we moved to the end of the region. while Allocation_Maps.Has_Element (Iter) loop Addr := Allocation_Maps.Key (Iter); exit when Addr > To; Pos := Into.Find (Addr); if not Allocation_Maps.Has_Element (Pos) then Into.Insert (Addr, Allocation_Maps.Element (Iter)); end if; Allocation_Maps.Next (Iter); end loop; end Find; end MAT.Memory.Tools;
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Memory.Tools is -- ------------------------------ -- Collect the information about memory slot sizes for the memory slots in the map. -- ------------------------------ procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map) is procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type); procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is pragma Unreferenced (Size); begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is pragma Unreferenced (Addr); Pos : constant Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; Iter : Allocation_Cursor := Memory.First; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is Iter : MAT.Memory.Allocation_Cursor := Memory.Ceiling (From); Pos : MAT.Memory.Allocation_Cursor; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; begin -- If there was no slot with the ceiling From address, we have to start from the last -- node because the memory slot may intersect our region. if not Allocation_Maps.Has_Element (Iter) then Iter := Memory.Last; if not Allocation_Maps.Has_Element (Iter) then return; end if; Addr := Allocation_Maps.Key (Iter); Size := Allocation_Maps.Element (Iter).Size; if Addr + Size < From then return; end if; end if; -- Move backward until the previous memory slot does not overlap anymore our region. -- In theory, going backward once is enough but if there was a target malloc issue, -- several malloc may overlap the same region (which is bad for the target). loop Pos := Allocation_Maps.Previous (Iter); exit when not Allocation_Maps.Has_Element (Pos); Addr := Allocation_Maps.Key (Pos); Size := Allocation_Maps.Element (Pos).Size; exit when Addr + Size < From; Iter := Pos; end loop; -- Add the memory slots until we moved to the end of the region. while Allocation_Maps.Has_Element (Iter) loop Addr := Allocation_Maps.Key (Iter); exit when Addr > To; Pos := Into.Find (Addr); if not Allocation_Maps.Has_Element (Pos) then Into.Insert (Addr, Allocation_Maps.Element (Iter)); end if; Allocation_Maps.Next (Iter); end loop; end Find; end MAT.Memory.Tools;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d1474d722d1a3ce0b57a5d68cae88b7e3c8ff62f
src/ado-schemas.adb
src/ado-schemas.adb
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Equal_Case_Insensitive; package body ADO.Schemas is procedure Free is new Ada.Unchecked_Deallocation (Object => Column, Name => Column_Definition); procedure Free is new Ada.Unchecked_Deallocation (Object => Table, Name => Table_Definition); procedure Free is new Ada.Unchecked_Deallocation (Object => Schema, Name => Schema_Access); -- ------------------------------ -- Get the hash value associated with the class mapping. -- ------------------------------ function Hash (Mapping : Class_Mapping_Access) return Ada.Containers.Hash_Type is begin if Mapping = null then return 0; else return Util.Strings.Hash (Mapping.Table); end if; end Hash; -- ------------------------------ -- Column Representation -- ------------------------------ -- ------------------------------ -- Get the column name -- ------------------------------ function Get_Name (Column : Column_Definition) return String is begin return To_String (Column.Name); end Get_Name; -- ------------------------------ -- Get the column type -- ------------------------------ function Get_Type (Column : Column_Definition) return Column_Type is begin return Column.Col_Type; end Get_Type; -- ------------------------------ -- Get the default column value -- ------------------------------ function Get_Default (Column : Column_Definition) return String is begin return To_String (Column.Default); end Get_Default; -- ------------------------------ -- Get the column collation (for string based columns) -- ------------------------------ function Get_Collation (Column : Column_Definition) return String is begin return To_String (Column.Collation); end Get_Collation; -- ------------------------------ -- Check whether the column can be null -- ------------------------------ function Is_Null (Column : Column_Definition) return Boolean is begin return Column.Is_Null; end Is_Null; -- ------------------------------ -- Check whether the column is an unsigned number -- ------------------------------ function Is_Unsigned (Column : Column_Definition) return Boolean is begin return Column.Is_Unsigned; end Is_Unsigned; -- ------------------------------ -- Returns true if the column can hold a binary string -- ------------------------------ function Is_Binary (Column : Column_Definition) return Boolean is begin return Column.Is_Binary; end Is_Binary; -- ------------------------------ -- Get the column length -- ------------------------------ function Get_Size (Column : Column_Definition) return Natural is begin return Column.Size; end Get_Size; -- ------------------------------ -- Column iterator -- ------------------------------ -- ------------------------------ -- Returns true if the iterator contains more column -- ------------------------------ function Has_Element (Cursor : Column_Cursor) return Boolean is begin return Cursor.Current /= null; end Has_Element; -- ------------------------------ -- Move to the next column -- ------------------------------ procedure Next (Cursor : in out Column_Cursor) is begin if Cursor.Current /= null then Cursor.Current := Cursor.Current.Next_Column; end if; end Next; -- ------------------------------ -- Get the current column definition -- ------------------------------ function Element (Cursor : Column_Cursor) return Column_Definition is begin return Cursor.Current; end Element; -- ------------------------------ -- Table Representation -- ------------------------------ -- ------------------------------ -- Get the table name -- ------------------------------ function Get_Name (Table : Table_Definition) return String is begin return To_String (Table.Name); end Get_Name; -- ------------------------------ -- Get the column iterator -- ------------------------------ function Get_Columns (Table : Table_Definition) return Column_Cursor is begin return Column_Cursor '(Current => Table.First_Column); end Get_Columns; -- ------------------------------ -- Find the column having the given name -- ------------------------------ function Find_Column (Table : Table_Definition; Name : String) return Column_Definition is Column : Column_Definition := Table.First_Column; begin while Column /= null loop if Ada.Strings.Equal_Case_Insensitive (To_String (Column.Name), Name) then return Column; end if; Column := Column.Next_Column; end loop; return null; end Find_Column; -- ------------------------------ -- Table iterator -- ------------------------------ -- ------------------------------ -- Returns true if the iterator contains more tables -- ------------------------------ function Has_Element (Cursor : Table_Cursor) return Boolean is begin return Cursor.Current /= null; end Has_Element; -- ------------------------------ -- Move to the next column -- ------------------------------ procedure Next (Cursor : in out Table_Cursor) is begin if Cursor.Current /= null then Cursor.Current := Cursor.Current.Next_Table; end if; end Next; -- ------------------------------ -- Get the current table definition -- ------------------------------ function Element (Cursor : Table_Cursor) return Table_Definition is begin return Cursor.Current; end Element; -- ------------------------------ -- Database Schema -- ------------------------------ -- ------------------------------ -- Find a table knowing its name -- ------------------------------ function Find_Table (Schema : Schema_Definition; Name : String) return Table_Definition is Table : Table_Definition; begin if Schema.Schema /= null then Table := Schema.Schema.First_Table; while Table /= null loop if Ada.Strings.Equal_Case_Insensitive (To_String (Table.Name), Name) then return Table; end if; Table := Table.Next_Table; end loop; end if; return null; end Find_Table; function Get_Tables (Schema : Schema_Definition) return Table_Cursor is begin if Schema.Schema = null then return Table_Cursor '(Current => null); else return Table_Cursor '(Current => Schema.Schema.First_Table); end if; end Get_Tables; procedure Finalize (Schema : in out Schema_Definition) is begin if Schema.Schema /= null then declare Table : Table_Definition; Column : Column_Definition; begin loop Table := Schema.Schema.First_Table; exit when Table = null; loop Column := Table.First_Column; exit when Column = null; Table.First_Column := Column.Next_Column; Free (Column); end loop; Schema.Schema.First_Table := Table.Next_Table; Free (Table); end loop; end; Free (Schema.Schema); end if; end Finalize; end ADO.Schemas;
----------------------------------------------------------------------- -- ado.schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Strings.Equal_Case_Insensitive; package body ADO.Schemas is procedure Free is new Ada.Unchecked_Deallocation (Object => Column, Name => Column_Definition); procedure Free is new Ada.Unchecked_Deallocation (Object => Table, Name => Table_Definition); procedure Free is new Ada.Unchecked_Deallocation (Object => Schema, Name => Schema_Access); -- ------------------------------ -- Get the hash value associated with the class mapping. -- ------------------------------ function Hash (Mapping : Class_Mapping_Access) return Ada.Containers.Hash_Type is begin if Mapping = null then return 0; else return Util.Strings.Hash (Mapping.Table); end if; end Hash; -- ------------------------------ -- Column Representation -- ------------------------------ -- ------------------------------ -- Get the column name -- ------------------------------ function Get_Name (Column : Column_Definition) return String is begin return To_String (Column.Name); end Get_Name; -- ------------------------------ -- Get the column type -- ------------------------------ function Get_Type (Column : Column_Definition) return Column_Type is begin return Column.Col_Type; end Get_Type; -- ------------------------------ -- Get the default column value -- ------------------------------ function Get_Default (Column : Column_Definition) return String is begin return To_String (Column.Default); end Get_Default; -- ------------------------------ -- Get the column collation (for string based columns) -- ------------------------------ function Get_Collation (Column : Column_Definition) return String is begin return To_String (Column.Collation); end Get_Collation; -- ------------------------------ -- Check whether the column can be null -- ------------------------------ function Is_Null (Column : Column_Definition) return Boolean is begin return Column.Is_Null; end Is_Null; -- ------------------------------ -- Check whether the column is an unsigned number -- ------------------------------ function Is_Unsigned (Column : Column_Definition) return Boolean is begin return Column.Is_Unsigned; end Is_Unsigned; -- ------------------------------ -- Returns true if the column can hold a binary string -- ------------------------------ function Is_Binary (Column : Column_Definition) return Boolean is begin return Column.Is_Binary; end Is_Binary; -- ------------------------------ -- Returns true if the column is a primary key. -- ------------------------------ function Is_Primary (Column : Column_Definition) return Boolean is begin return Column.Is_Primary; end Is_Primary; -- ------------------------------ -- Get the column length -- ------------------------------ function Get_Size (Column : Column_Definition) return Natural is begin return Column.Size; end Get_Size; -- ------------------------------ -- Column iterator -- ------------------------------ -- ------------------------------ -- Returns true if the iterator contains more column -- ------------------------------ function Has_Element (Cursor : Column_Cursor) return Boolean is begin return Cursor.Current /= null; end Has_Element; -- ------------------------------ -- Move to the next column -- ------------------------------ procedure Next (Cursor : in out Column_Cursor) is begin if Cursor.Current /= null then Cursor.Current := Cursor.Current.Next_Column; end if; end Next; -- ------------------------------ -- Get the current column definition -- ------------------------------ function Element (Cursor : Column_Cursor) return Column_Definition is begin return Cursor.Current; end Element; -- ------------------------------ -- Table Representation -- ------------------------------ -- ------------------------------ -- Get the table name -- ------------------------------ function Get_Name (Table : Table_Definition) return String is begin return To_String (Table.Name); end Get_Name; -- ------------------------------ -- Get the column iterator -- ------------------------------ function Get_Columns (Table : Table_Definition) return Column_Cursor is begin return Column_Cursor '(Current => Table.First_Column); end Get_Columns; -- ------------------------------ -- Find the column having the given name -- ------------------------------ function Find_Column (Table : Table_Definition; Name : String) return Column_Definition is Column : Column_Definition := Table.First_Column; begin while Column /= null loop if Ada.Strings.Equal_Case_Insensitive (To_String (Column.Name), Name) then return Column; end if; Column := Column.Next_Column; end loop; return null; end Find_Column; -- ------------------------------ -- Table iterator -- ------------------------------ -- ------------------------------ -- Returns true if the iterator contains more tables -- ------------------------------ function Has_Element (Cursor : Table_Cursor) return Boolean is begin return Cursor.Current /= null; end Has_Element; -- ------------------------------ -- Move to the next column -- ------------------------------ procedure Next (Cursor : in out Table_Cursor) is begin if Cursor.Current /= null then Cursor.Current := Cursor.Current.Next_Table; end if; end Next; -- ------------------------------ -- Get the current table definition -- ------------------------------ function Element (Cursor : Table_Cursor) return Table_Definition is begin return Cursor.Current; end Element; -- ------------------------------ -- Database Schema -- ------------------------------ -- ------------------------------ -- Find a table knowing its name -- ------------------------------ function Find_Table (Schema : Schema_Definition; Name : String) return Table_Definition is Table : Table_Definition; begin if Schema.Schema /= null then Table := Schema.Schema.First_Table; while Table /= null loop if Ada.Strings.Equal_Case_Insensitive (To_String (Table.Name), Name) then return Table; end if; Table := Table.Next_Table; end loop; end if; return null; end Find_Table; function Get_Tables (Schema : Schema_Definition) return Table_Cursor is begin if Schema.Schema = null then return Table_Cursor '(Current => null); else return Table_Cursor '(Current => Schema.Schema.First_Table); end if; end Get_Tables; procedure Finalize (Schema : in out Schema_Definition) is begin if Schema.Schema /= null then declare Table : Table_Definition; Column : Column_Definition; begin loop Table := Schema.Schema.First_Table; exit when Table = null; loop Column := Table.First_Column; exit when Column = null; Table.First_Column := Column.Next_Column; Free (Column); end loop; Schema.Schema.First_Table := Table.Next_Table; Free (Table); end loop; end; Free (Schema.Schema); end if; end Finalize; end ADO.Schemas;
Implement the Is_Primary function
Implement the Is_Primary function
Ada
apache-2.0
stcarrez/ada-ado
36e5e13218458ef2d0730154ebc1c04eedbf8d05
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) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; overriding procedure Add_File (Into : in out File_Queue; Path : in String; Element : in File) is begin Into.Queue.Enqueue (Element); end Add_File; overriding procedure Add_Directory (Into : in out File_Queue; Path : in String; Name : in String) is begin Into.Directories.Append (Util.Files.Compose (Path, Name)); end Add_Directory; procedure Scan_Files (Path : in String; Into : in out Directory) is Iter : File_Vectors.Cursor := Into.Files.First; procedure Compute_Sha1 (Item : in out File) is begin Compute_Sha1 (Path, Item); end Compute_Sha1; begin while File_Vectors.Has_Element (Iter) loop Into.Files.Update_Element (Iter, Compute_Sha1'Access); File_Vectors.Next (Iter); end loop; end Scan_Files; procedure Scan_Children (Path : in String; Into : in out Directory) is procedure Update (Dir : in out Directory) is use Ada.Strings.Unbounded; use type Ada.Directories.File_Size; begin Scan (Path & "/" & To_String (Dir.Name), Dir); Into.Tot_Files := Into.Tot_Files + Dir.Tot_Files; Into.Tot_Size := Into.Tot_Size + Dir.Tot_Size; Into.Tot_Dirs := Into.Tot_Dirs + Dir.Tot_Dirs; end Update; begin if Into.Children /= null then declare Iter : Directory_Vectors.Cursor := Into.Children.First; begin while Directory_Vectors.Has_Element (Iter) loop Into.Children.Update_Element (Iter, Update'Access); Directory_Vectors.Next (Iter); end loop; end; end if; end Scan_Children; procedure Scan (Path : in String; Into : in out Directory) is use Ada.Directories; Filter : constant Ada.Directories.Filter_Type := (Ordinary_File => True, Ada.Directories.Directory => True, Special_File => False); Search : Search_Type; Ent : Directory_Entry_Type; New_File : File; Child : Directory; begin Into.Tot_Size := 0; Into.Tot_Files := 0; Into.Tot_Dirs := 0; Start_Search (Search, Directory => Path, Pattern => "*", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Kind : constant File_Kind := Ada.Directories.Kind (Ent); begin if Kind = Ordinary_File then New_File.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); begin New_File.Size := Ada.Directories.Size (Ent); exception when Constraint_Error => New_File.Size := Ada.Directories.File_Size (Interfaces.Unsigned_32'Last); end; Into.Files.Append (New_File); if New_File.Size > 0 then begin Into.Tot_Size := Into.Tot_Size + New_File.Size; exception when Constraint_Error => Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (New_File.Size) & " for " & Path & "/" & Name); Ada.Text_IO.Put_Line ("Size: " & Ada.Directories.File_Size'Image (Into.Tot_Size)); end; end if; Into.Tot_Files := Into.Tot_Files + 1; elsif Name /= "." and Name /= ".." then if Into.Children = null then Into.Children := new Directory_Vector; end if; Child.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name); Into.Children.Append (Child); Into.Tot_Dirs := Into.Tot_Dirs + 1; end if; end; end loop; Scan_Children (Path, Into); Scan_Files (Path, Into); exception when E : others => Log.Error ("Exception ", E); end Scan; 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 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) return String is begin return Util.Files.Compose (Ada.Strings.Unbounded.To_String (Element.Path), Ada.Strings.Unbounded.To_String (Element.Name)); end Get_Path; overriding procedure Add_File (Into : in out File_Queue; Path : in String; Element : in File) is begin Into.Queue.Enqueue (Element); end Add_File; overriding procedure Add_Directory (Into : in out File_Queue; Path : in String; Name : in String) is begin Into.Directories.Append (Util.Files.Compose (Path, Name)); end Add_Directory; end Babel.Files;
Remove the old Scan_Files, Scan_Children and Scan operations
Remove the old Scan_Files, Scan_Children and Scan operations
Ada
apache-2.0
stcarrez/babel
6c80ddcecde5b8f4fe8b2e1fde89017f1df0195f
src/babel-files.adb
src/babel-files.adb
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- 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; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; end Babel.Files;
-- bkp-files -- File and directories ----------------------------------------------------------------------- -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Files; with Util.Encoders.Base16; package body Babel.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files"); Hex_Encoder : Util.Encoders.Base16.Encoder; -- ------------------------------ -- 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; -- ------------------------------ -- Allocate a Directory_Type entry with the given name for the directory. -- ------------------------------ function Allocate (Name : in String; Dir : in Directory_Type) return Directory_Type is use Ada.Strings.Unbounded; Result : constant Directory_Type := new Directory '(Len => Name'Length, Id => NO_IDENTIFIER, Parent => Dir, Name => Name, others => <>); begin if Dir /= null then Result.Path := To_Unbounded_String (Util.Files.Compose (To_String (Dir.Path), Name)); end if; return Result; end Allocate; -- ------------------------------ -- Return true if the file was modified and need a backup. -- ------------------------------ function Is_Modified (Element : in File_Type) return Boolean is use type ADO.Identifier; begin if Element.Id = NO_IDENTIFIER then return True; elsif (Element.Status and FILE_MODIFIED) /= 0 then return True; else return False; end if; end Is_Modified; -- ------------------------------ -- Set the file as modified. -- ------------------------------ procedure Set_Modified (Element : in File_Type) is begin Element.Status := Element.Status or FILE_MODIFIED; end Set_Modified; -- ------------------------------ -- Set the SHA1 signature that was computed for this file. -- If the computed signature is different from the current signature, -- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag -- is set on the file. -- ------------------------------ procedure Set_Signature (Element : in File_Type; Signature : in Util.Encoders.SHA1.Hash_Array) is use type Util.Encoders.SHA1.Hash_Array; begin if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then Element.Status := Element.Status or FILE_MODIFIED; end if; Element.Status := Element.Status or FILE_HAS_SHA1; Element.SHA1 := Signature; end Set_Signature; -- ------------------------------ -- Set the file size. If the new size is different, the FILE_MODIFIED -- flag is set on the file. -- ------------------------------ procedure Set_Size (Element : in File_Type; Size : in File_Size) is begin if Element.Size /= Size then Element.Size := Size; Element.Status := Element.Status or FILE_MODIFIED; end if; end Set_Size; -- ------------------------------ -- Return the path for the file. -- ------------------------------ function Get_Path (Element : in File_Type) return String is begin if Element.Dir = null then return Element.Name; else return Util.Files.Compose (Get_Path (Element.Dir), Element.Name); end if; end Get_Path; -- ------------------------------ -- Return the path for the directory. -- ------------------------------ function Get_Path (Element : in Directory_Type) return String is begin return Ada.Strings.Unbounded.To_String (Element.Path); end Get_Path; -- ------------------------------ -- Return the SHA1 signature computed for the file. -- ------------------------------ function Get_SHA1 (Element : in File_Type) return String is begin return Hex_Encoder.Transform (Element.SHA1); end Get_SHA1; -- ------------------------------ -- Add the file with the given name in the container. -- ------------------------------ overriding procedure Add_File (Into : in out Default_Container; Element : in File_Type) is begin Into.Files.Append (Element); end Add_File; -- ------------------------------ -- Add the directory with the given name in the container. -- ------------------------------ overriding procedure Add_Directory (Into : in out Default_Container; Element : in Directory_Type) is begin Into.Dirs.Append (Element); end Add_Directory; -- ------------------------------ -- Create a new file instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return File_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Create a new directory instance with the given name in the container. -- ------------------------------ overriding function Create (Into : in Default_Container; Name : in String) return Directory_Type is begin return Allocate (Name => Name, Dir => Into.Current); end Create; -- ------------------------------ -- Find the file with the given name in this file container. -- Returns NO_FILE if the file was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return File_Type is pragma Unreferenced (From, Name); begin return NO_FILE; end Find; -- ------------------------------ -- Find the directory with the given name in this file container. -- Returns NO_DIRECTORY if the directory was not found. -- ------------------------------ overriding function Find (From : in Default_Container; Name : in String) return Directory_Type is pragma Unreferenced (From, Name); begin return NO_DIRECTORY; end Find; -- ------------------------------ -- Set the directory object associated with the container. -- ------------------------------ procedure Set_Directory (Into : in out Default_Container; Directory : in Directory_Type) is begin Into.Current := Directory; Into.Files.Clear; Into.Dirs.Clear; end Set_Directory; -- ------------------------------ -- Execute the Process procedure on each directory found in the container. -- ------------------------------ overriding procedure Each_Directory (Container : in Default_Container; Process : not null access procedure (Dir : in Directory_Type)) is Iter : Directory_Vectors.Cursor := Container.Dirs.First; begin while Directory_Vectors.Has_Element (Iter) loop Process (Directory_Vectors.Element (Iter)); Directory_Vectors.Next (Iter); end loop; end Each_Directory; end Babel.Files;
Implement the Each_Directory operation
Implement the Each_Directory operation
Ada
apache-2.0
stcarrez/babel
156fb42e4ba237f84965cc800acd0bb338de8281
0005.adb
0005.adb
---------------------------------------------------------------------- -- Ada for POSIX (AdaFPX) ---------------------------------------------------------------------- -- Warren W. Gay VE3WWG Tue Dec 3 18:49:48 2013 -- -- This is generated source code. Edit at your own risk. package body Posix is function C_Last(C_String: String) return Natural is begin for X in C_String'Range loop if Character'Pos(C_String(X)) = 0 then return Natural(X-1); end if; end loop; return C_String'Last; end C_Last; function To_Count(Status: ssize_t) return Natural is begin if Status <= 0 then return 0; else return Natural(Status); end if; end To_Count; pragma Inline(To_Count); function To_Count(Status: int_t) return Natural is begin if Status <= 0 then return 0; else return Natural(Status); end if; end To_Count; pragma Inline(To_Count); function C_Error(Ret_Val: int_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if Ret_Val >= 0 then return 0; else return c_errno; end if; end C_Error; pragma Inline(C_Error); function C_Error(Ret_Val: ssize_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if Ret_Val >= 0 then return 0; else return c_errno; end if; end C_Error; pragma Inline(C_Error); function C_Error(PID: pid_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if PID /= -1 then return 0; else return c_errno; end if; end C_Error; pragma Inline(C_Error); function C_Error(Ret_Val: clock_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin pragma Warnings(Off); if Ret_Val < 0 or else Ret_Val = clock_t'Last then return c_errno; else return 0; end if; pragma Warnings(On); end C_Error; function C_Error(Ret_Val: sig_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if Ret_Val = SIG_ERR then return c_errno; else return 0; end if; end C_Error; function C_Error(Ret_Val: mode_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin pragma Warnings(Off); if Ret_Val < 0 or else Ret_Val = mode_t'Last then return c_errno; else return 0; end if; pragma Warnings(On); end C_Error; function C_String(Ada_String: String) return String is T : String(Ada_String'First..Ada_String'Last+1); begin T(T'First..T'Last-1) := Ada_String; T(T'Last) := Character'Val(0); return T; end C_String; function Ada_String(C_String: String) return String is begin for X in C_String'Range loop if Character'Pos(C_String(X)) = 0 then return C_String(C_String'First..X-1); end if; end loop; return C_String; end Ada_String; function Pos_PID(Status: int_t) return pid_t is begin if Status >= 0 then return pid_t(Status); else return 0; end if; end Pos_PID; pragma Inline(Pos_PID); function Neg_PID(Status: int_t) return pid_t is begin if Status < 0 then return pid_t(-Status); else return 0; end if; end Neg_PID; pragma Inline(Neg_PID); function Argv_Length(Argvs: String) return Natural is Count : Natural := 0; begin for X in Argvs'Range loop if Character'Pos(Argvs(x)) = 0 then Count := Count + 1; end if; end loop; return Count + 1; end Argv_Length; function Argv_Length(Argv: argv_array) return Natural is use System; begin for X in Argv'Range loop if Argv(X) = System.Null_Address then return X - Argv'First; end if; end loop; return Argv'Length; end Argv_Length; procedure Find_Nul(S: String; X: out Natural; Found: out Boolean) is begin for Y in S'Range loop if Character'Pos(S(Y)) = 0 then X := Y; Found := True; end if; end loop; X := S'Last; Found := False; end Find_Nul; function To_Argv(Argvs: String) return argv_array is Count : constant Natural := Argv_Length(Argvs); X : Natural := Argvs'First; Y : Natural; Found : Boolean; begin declare Argv : argv_array(0..Count-1); Arg_X : Natural := Argv'First; begin while X <= Argvs'Last loop Find_Nul(Argvs(X..Argv'Last),Y,Found); exit when not Found; Argv(Arg_X) := Argvs(X)'Address; Arg_X := Arg_X + 1; X := Y + 1; end loop; Argv(Arg_X) := System.Null_Address; return Argv; end; end To_Argv; procedure To_Argv(Argvs: String; Argv: out argv_array) is Count : Natural := Argv_Length(Argvs); Arg_X : Natural := Argv'First; C : Natural := 0; X : Natural := Argvs'First; Y : Natural; Found : Boolean; begin pragma Assert(Argv'Length>1); if Count > Argv'Length then Count := Argv'Length - 1; end if; while C < Count and X <= Argvs'Last loop Find_Nul(Argvs(X..Argv'Last),Y,Found); exit when not Found; Argv(Arg_X) := Argvs(X)'Address; Arg_X := Arg_X + 1; X := Y + 1; C := C + 1; end loop; Argv(Arg_X) := System.Null_Address; end To_Argv; function To_Clock(Ticks: clock_t) return clock_t is begin pragma Warnings(Off); if Ticks < 0 or else Ticks = clock_t'Last then return 0; else return Ticks; end if; pragma Warnings(On); end To_Clock;
---------------------------------------------------------------------- -- Ada for POSIX (AdaFPX) ---------------------------------------------------------------------- -- Warren W. Gay VE3WWG Tue Dec 3 18:49:48 2013 -- -- This is generated source code. Edit at your own risk. package body Posix is function "="(L,R : DIR) return Boolean is use System; begin return System.Address(L) = System.Address(R); end "="; function C_Last(C_String: String) return Natural is begin for X in C_String'Range loop if Character'Pos(C_String(X)) = 0 then return Natural(X-1); end if; end loop; return C_String'Last; end C_Last; function To_Count(Status: ssize_t) return Natural is begin if Status <= 0 then return 0; else return Natural(Status); end if; end To_Count; pragma Inline(To_Count); function To_Count(Status: int_t) return Natural is begin if Status <= 0 then return 0; else return Natural(Status); end if; end To_Count; pragma Inline(To_Count); function C_Error(Ret_Val: int_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if Ret_Val >= 0 then return 0; else return c_errno; end if; end C_Error; function C_Error(Ret_Val: long_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if Ret_Val >= 0 then return 0; else return c_errno; end if; end C_Error; pragma Inline(C_Error); function C_Error(Ret_Val: ssize_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if Ret_Val >= 0 then return 0; else return c_errno; end if; end C_Error; pragma Inline(C_Error); function C_Error(PID: pid_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if PID /= -1 then return 0; else return c_errno; end if; end C_Error; pragma Inline(C_Error); function C_Error(Ret_Val: clock_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin pragma Warnings(Off); if Ret_Val < 0 or else Ret_Val = clock_t'Last then return c_errno; else return 0; end if; pragma Warnings(On); end C_Error; function C_Error(Ret_Val: sig_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if Ret_Val = SIG_ERR then return c_errno; else return 0; end if; end C_Error; function C_Error(Ret_Val: mode_t) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin pragma Warnings(Off); if Ret_Val < 0 or else Ret_Val = mode_t'Last then return c_errno; else return 0; end if; pragma Warnings(On); end C_Error; function C_Error(Ret_Val: DIR) return errno_t is function c_errno return errno_t; pragma Import(C,c_errno,"c_errno"); begin if Ret_Val /= Null_DIR then return 0; else return c_errno; end if; end C_Error; function C_String(Ada_String: String) return String is T : String(Ada_String'First..Ada_String'Last+1); begin T(T'First..T'Last-1) := Ada_String; T(T'Last) := Character'Val(0); return T; end C_String; function Ada_String(C_String: String) return String is begin for X in C_String'Range loop if Character'Pos(C_String(X)) = 0 then return C_String(C_String'First..X-1); end if; end loop; return C_String; end Ada_String; function Pos_PID(Status: int_t) return pid_t is begin if Status >= 0 then return pid_t(Status); else return 0; end if; end Pos_PID; pragma Inline(Pos_PID); function Neg_PID(Status: int_t) return pid_t is begin if Status < 0 then return pid_t(-Status); else return 0; end if; end Neg_PID; pragma Inline(Neg_PID); function Argv_Length(Argvs: String) return Natural is Count : Natural := 0; begin for X in Argvs'Range loop if Character'Pos(Argvs(x)) = 0 then Count := Count + 1; end if; end loop; return Count + 1; end Argv_Length; function Argv_Length(Argv: argv_array) return Natural is use System; begin for X in Argv'Range loop if Argv(X) = System.Null_Address then return X - Argv'First; end if; end loop; return Argv'Length; end Argv_Length; procedure Find_Nul(S: String; X: out Natural; Found: out Boolean) is begin for Y in S'Range loop if Character'Pos(S(Y)) = 0 then X := Y; Found := True; end if; end loop; X := S'Last; Found := False; end Find_Nul; function To_Argv(Argvs: String) return argv_array is Count : constant Natural := Argv_Length(Argvs); X : Natural := Argvs'First; Y : Natural; Found : Boolean; begin declare Argv : argv_array(0..Count-1); Arg_X : Natural := Argv'First; begin while X <= Argvs'Last loop Find_Nul(Argvs(X..Argv'Last),Y,Found); exit when not Found; Argv(Arg_X) := Argvs(X)'Address; Arg_X := Arg_X + 1; X := Y + 1; end loop; Argv(Arg_X) := System.Null_Address; return Argv; end; end To_Argv; procedure To_Argv(Argvs: String; Argv: out argv_array) is Count : Natural := Argv_Length(Argvs); Arg_X : Natural := Argv'First; C : Natural := 0; X : Natural := Argvs'First; Y : Natural; Found : Boolean; begin pragma Assert(Argv'Length>1); if Count > Argv'Length then Count := Argv'Length - 1; end if; while C < Count and X <= Argvs'Last loop Find_Nul(Argvs(X..Argv'Last),Y,Found); exit when not Found; Argv(Arg_X) := Argvs(X)'Address; Arg_X := Arg_X + 1; X := Y + 1; C := C + 1; end loop; Argv(Arg_X) := System.Null_Address; end To_Argv; function To_Clock(Ticks: clock_t) return clock_t is begin pragma Warnings(Off); if Ticks < 0 or else Ticks = clock_t'Last then return 0; else return Ticks; end if; pragma Warnings(On); end To_Clock;
Support for more types
Support for more types
Ada
lgpl-2.1
ve3wwg/adafpx,ve3wwg/adafpx
648728bb8d98a92690fd3535e562b0e748e4a3e6
matp/src/matp.adb
matp/src/matp.adb
----------------------------------------------------------------------- -- mat-types -- Global types -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; procedure Matp is Target : MAT.Targets.Target_Type; Console : aliased MAT.Consoles.Text.Console_Type; begin Target.Console (Console'Unchecked_Access); Target.Initialize_Options; MAT.Commands.Initialize_Files (Target); Target.Start; Target.Interactive; Target.Stop; exception when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error => Target.Stop; end Matp;
----------------------------------------------------------------------- -- matp -- Main program -- 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.IO_Exceptions; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; procedure Matp is Target : MAT.Targets.Target_Type; Console : aliased MAT.Consoles.Text.Console_Type; begin Target.Console (Console'Unchecked_Access); Target.Initialize_Options; MAT.Commands.Initialize_Files (Target); Target.Start; Target.Interactive; Target.Stop; exception when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error => Target.Stop; end Matp;
Fix comment header
Fix comment header
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
952c1f36dcb0fa25aaad2fb34da08065ea2326f3
src/sys/streams/util-streams-buffered-encoders.ads
src/sys/streams/util-streams-buffered-encoders.ads
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders; -- == Encoding Streams == -- The <tt>Encoding_Stream</tt> tagged record represents a stream with encoding capabilities. -- The stream passes the data to be written to the <tt>Transformer</tt> interface that -- allows to make transformations on the data before being written. -- -- Encode : Util.Streams.Buffered.Encoders.Encoding_Stream; -- -- The encoding stream manages a buffer that is used to hold the encoded data before it is -- written to the target stream. The <tt>Initialize</tt> procedure must be called to indicate -- the target stream, the size of the buffer and the encoding format to be used. -- -- Encode.Initialize (Output => File'Access, Size => 4096, Format => "base64"); -- package Util.Streams.Buffered.Encoders is pragma Preelaborate; -- ----------------------- -- Encoding stream -- ----------------------- -- The <b>Encoding_Stream</b> is an output stream which uses an encoder to -- transform the data before writing it to the output. The transformer can -- change the data by encoding it in Base64, Base16 or encrypting it. type Encoding_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with private; -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Encoding_Stream; Output : access Output_Stream'Class; Size : in Natural; Format : in String); -- Close the sink. overriding procedure Close (Stream : in out Encoding_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Encoding_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Encoding_Stream); private type Encoding_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record Transform : Util.Encoders.Transformer_Access; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Encoding_Stream); end Util.Streams.Buffered.Encoders;
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders; -- == Encoding Streams == -- The <tt>Encoding_Stream</tt> tagged record represents a stream with encoding capabilities. -- The stream passes the data to be written to the <tt>Transformer</tt> interface that -- allows to make transformations on the data before being written. -- -- Encode : Util.Streams.Buffered.Encoders.Encoding_Stream; -- -- The encoding stream manages a buffer that is used to hold the encoded data before it is -- written to the target stream. The <tt>Initialize</tt> procedure must be called to indicate -- the target stream, the size of the buffer and the encoding format to be used. -- -- Encode.Initialize (Output => File'Access, Size => 4096, Format => "base64"); -- generic type Encoder is limited new Util.Encoders.Transformer with private; package Util.Streams.Buffered.Encoders is -- ----------------------- -- Encoding stream -- ----------------------- -- The <b>Encoding_Stream</b> is an output stream which uses an encoder to -- transform the data before writing it to the output. The transformer can -- change the data by encoding it in Base64, Base16 or encrypting it. type Encoder_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record Transform : Encoder; end record; -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. overriding procedure Initialize (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Encoder_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Encoder_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Encoder_Stream); end Util.Streams.Buffered.Encoders;
Change the Encoders package to a generic package that must be instantiated with an encoder
Change the Encoders package to a generic package that must be instantiated with an encoder
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
229fe2770a3c102a6e0545d87f84324a497fe8a9
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; use MAT.Types; with MAT.Memory.Events.Servant; package body MAT.Memory.Clients is use MAT.Memory.Events.Servant; procedure Create_Instance (Refs : in ClientInfo_Ref_Map) is -- Adapter : Manager := Get_Manager (Refs); -- Client : Client_Memory := new Client_Memory; begin -- Register_Client (Refs, "memory", Client.all'Access); -- Register_Servant (Adapter, Proxy); null; end Create_Instance; end MAT.Memory.Clients;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; use MAT.Types; package body MAT.Memory.Targets is procedure Create_Instance (Refs : in ClientInfo_Ref_Map) is -- Adapter : Manager := Get_Manager (Refs); -- Client : Client_Memory := new Client_Memory; begin -- Register_Client (Refs, "memory", Client.all'Access); -- Register_Servant (Adapter, Proxy); null; end Create_Instance; end MAT.Memory.Targets;
Rename package to MAT.Memory.Targets
Rename package to MAT.Memory.Targets
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
357257a499d9f5db6daafe1eed59e4c61bdc4fb0
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
awa/plugins/awa-questions/regtests/awa-questions-modules-tests.adb
----------------------------------------------------------------------- -- awa-questions-modules-tests -- Unit tests for storage service -- Copyright (C) 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.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.Modules.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.Services.Delete_Question", Test_Delete_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_Module; 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 deletion of a question. -- ------------------------------ procedure Test_Delete_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_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I search strings in Ada?"); Q.Set_Description ("I have two strings that I want to search. % does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); T.Manager.Delete_Question (Q); end Test_Delete_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is use AWA.Questions.Models; use AWA.Questions.Beans; 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"); T.Assert (List.all in Questions.Beans.Question_List_Bean'Class, "The Create_Question_List_Bean returns an invalid bean"); Count := Questions.Beans.Question_List_Bean'Class (List.all).Questions.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 Context.Set_Parameter ("id", "1"); 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.Modules.Tests;
----------------------------------------------------------------------- -- awa-questions-modules-tests -- Unit tests for storage service -- Copyright (C) 2013, 2014, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.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.Modules.Tests is use Util.Tests; 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.Services.Delete_Question", Test_Delete_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_Module; 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 deletion of a question. -- ------------------------------ procedure Test_Delete_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_Module; T.Assert (T.Manager /= null, "There is no question manager"); Q.Set_Title ("How can I search strings in Ada?"); Q.Set_Description ("I have two strings that I want to search. % does not work."); T.Manager.Save_Question (Q); T.Assert (Q.Is_Inserted, "The new question was not inserted"); T.Manager.Delete_Question (Q); end Test_Delete_Question; -- ------------------------------ -- Test list of questions. -- ------------------------------ procedure Test_List_Questions (T : in out Test) is 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"); T.Assert (List.all in Questions.Beans.Question_List_Bean'Class, "The Create_Question_List_Bean returns an invalid bean"); Count := Questions.Beans.Question_List_Bean'Class (List.all).Questions.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 Context.Set_Parameter ("id", "1"); 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.Modules.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
0ffedb570242832b272ef09ea1dae6f85529605f
src/wiki.ads
src/wiki.ads
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = Wiki = -- The Wiki engine parses a Wiki text in several Wiki syntax such as `MediaWiki`, -- `Creole`, `Markdown`, `Dotclear` and renders the result either in HTML, text or into -- another Wiki format. The Wiki engine is used in two steps: -- -- * The Wiki text is parsed according to its syntax to produce a Wiki Document instance. -- * The Wiki document is then rendered by a renderer to produce the final HTML, text. -- -- Through this process, it is possible to insert filters and plugins to customize the -- parsing and the rendering. -- -- [images/ada-wiki.png] -- -- The Ada Wiki engine is organized in several packages: -- -- * The [Wiki Streams](#wiki-streams) packages define the interface, types and operations -- for the Wiki engine to read the Wiki or HTML content and for the Wiki renderer to generate -- the HTML or text outputs. -- * The [Wiki parser](#wiki-parsers) is responsible for parsing HTML or Wiki content -- according to a selected Wiki syntax. It builds the final Wiki document through filters -- and plugins. -- * The [Wiki Filters](#wiki-filters) provides a simple filter framework that allows to plug -- specific filters when a Wiki document is parsed and processed. Filters are used for the -- table of content generation, for the HTML filtering, to collect words or links -- and so on. -- * The [Wiki Plugins](#wiki-plugins) defines the plugin interface that is used -- by the Wiki engine to provide pluggable extensions in the Wiki. Plugins are used -- for the Wiki template support, to hide some Wiki text content when it is rendered -- or to interact with other systems. -- * The Wiki documents and attributes are used for the representation of the Wiki -- document after the Wiki content is parsed. -- * The [Wiki renderers](@wiki-render) are the last packages which are used for the rendering -- of the Wiki document to produce the final HTML or text. -- -- @include-doc docs/Tutorial.md -- @include wiki-documents.ads -- @include wiki-attributes.ads -- @include wiki-parsers.ads -- @include wiki-filters.ads -- @include wiki-plugins.ads -- @include wiki-render.ads -- @include wiki-streams.ads package Wiki is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- Textile syntax -- https://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile SYNTAX_TEXTILE, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); -- Defines the possible text formats. type Format_Type is (BOLD, ITALIC, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT); type Format_Map is array (Format_Type) of Boolean; -- The possible HTML tags as described in HTML5 specification. type Html_Tag is ( -- Section 4.1 The root element ROOT_HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Deprecated tags but still used widely TT_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag) return String_Access; type Tag_Boolean_Array is array (Html_Tag) of Boolean; No_End_Tag : constant Tag_Boolean_Array := ( BASE_TAG => True, LINK_TAG => True, META_TAG => True, IMG_TAG => True, HR_TAG => True, BR_TAG => True, WBR_TAG => True, INPUT_TAG => True, KEYGEN_TAG => True, others => False); Tag_Omission : constant Tag_Boolean_Array := ( -- Section 4.4 Grouping content LI_TAG => True, DT_TAG => True, DD_TAG => True, -- Section 4.5 Text-level semantics RB_TAG => True, RT_TAG => True, RTC_TAG => True, RP_TAG => True, -- Section 4.9 Tabular data TH_TAG => True, TD_TAG => True, TR_TAG => True, TBODY_TAG => True, THEAD_TAG => True, TFOOT_TAG => True, OPTGROUP_TAG => True, OPTION_TAG => True, others => False); end Wiki;
----------------------------------------------------------------------- -- wiki -- Ada Wiki Engine -- Copyright (C) 2015, 2016, 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = Wiki = -- The Wiki engine parses a Wiki text in several Wiki syntax such as `MediaWiki`, -- `Creole`, `Markdown`, `Dotclear` and renders the result either in HTML, text or into -- another Wiki format. The Wiki engine is used in two steps: -- -- * The Wiki text is parsed according to its syntax to produce a Wiki Document instance. -- * The Wiki document is then rendered by a renderer to produce the final HTML, text. -- -- Through this process, it is possible to insert filters and plugins to customize the -- parsing and the rendering. -- -- [images/ada-wiki.png] -- -- The Ada Wiki engine is organized in several packages: -- -- * The [Wiki Streams](#wiki-streams) packages define the interface, types and operations -- for the Wiki engine to read the Wiki or HTML content and for the Wiki renderer to generate -- the HTML or text outputs. -- * The [Wiki parser](#wiki-parsers) is responsible for parsing HTML or Wiki content -- according to a selected Wiki syntax. It builds the final Wiki document through filters -- and plugins. -- * The [Wiki Filters](#wiki-filters) provides a simple filter framework that allows to plug -- specific filters when a Wiki document is parsed and processed. Filters are used for the -- table of content generation, for the HTML filtering, to collect words or links -- and so on. -- * The [Wiki Plugins](#wiki-plugins) defines the plugin interface that is used -- by the Wiki engine to provide pluggable extensions in the Wiki. Plugins are used -- for the Wiki template support, to hide some Wiki text content when it is rendered -- or to interact with other systems. -- * The Wiki documents and attributes are used for the representation of the Wiki -- document after the Wiki content is parsed. -- * The [Wiki renderers](@wiki-render) are the last packages which are used for the rendering -- of the Wiki document to produce the final HTML or text. -- -- @include-doc docs/Tutorial.md -- @include wiki-documents.ads -- @include wiki-attributes.ads -- @include wiki-parsers.ads -- @include wiki-filters.ads -- @include wiki-plugins.ads -- @include wiki-render.ads -- @include wiki-streams.ads package Wiki is pragma Preelaborate; -- Defines the possible wiki syntax supported by the parser. type Wiki_Syntax is ( -- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax SYNTAX_GOOGLE, -- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0 SYNTAX_CREOLE, -- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes SYNTAX_DOTCLEAR, -- PhpBB syntax http://wiki.phpbb.com/Help:Formatting SYNTAX_PHPBB, -- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting SYNTAX_MEDIA_WIKI, -- Markdown SYNTAX_MARKDOWN, -- Textile syntax -- https://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile SYNTAX_TEXTILE, -- A mix of the above SYNTAX_MIX, -- The input is plain possibly incorrect HTML. SYNTAX_HTML); -- Defines the possible text formats. type Format_Type is (BOLD, STRONG, ITALIC, EMPHASIS, CODE, SUPERSCRIPT, SUBSCRIPT, STRIKEOUT, PREFORMAT); type Format_Map is array (Format_Type) of Boolean; -- The possible HTML tags as described in HTML5 specification. type Html_Tag is ( -- Section 4.1 The root element ROOT_HTML_TAG, -- Section 4.2 Document metadata HEAD_TAG, TITLE_TAG, BASE_TAG, LINK_TAG, META_TAG, STYLE_TAG, -- Section 4.3 Sections BODY_TAG, ARTICLE_TAG, SECTION_TAG, NAV_TAG, ASIDE_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HEADER_TAG, FOOTER_TAG, ADDRESS_TAG, -- Section 4.4 Grouping content P_TAG, HR_TAG, PRE_TAG, BLOCKQUOTE_TAG, OL_TAG, UL_TAG, LI_TAG, DL_TAG, DT_TAG, DD_TAG, FIGURE_TAG, FIGCAPTION_TAG, DIV_TAG, MAIN_TAG, -- Section 4.5 Text-level semantics A_TAG, EM_TAG, STRONG_TAG, SMALL_TAG, S_TAG, CITE_TAG, Q_TAG, DFN_TAG, ABBR_TAG, DATA_TAG, TIME_TAG, CODE_TAG, VAR_TAG, SAMP_TAG, KBD_TAG, SUB_TAG, SUP_TAG, I_TAG, B_TAG, U_TAG, MARK_TAG, RUBY_TAG, RB_TAG, RT_TAG, RTC_TAG, RP_TAG, BDI_TAG, BDO_TAG, SPAN_TAG, BR_TAG, WBR_TAG, -- Section 4.6 Edits INS_TAG, DEL_TAG, -- Section 4.7 Embedded content IMG_TAG, IFRAME_TAG, EMBED_TAG, OBJECT_TAG, PARAM_TAG, VIDEO_TAG, AUDIO_TAG, SOURCE_TAG, TRACK_TAG, MAP_TAG, AREA_TAG, -- Section 4.9 Tabular data TABLE_TAG, CAPTION_TAG, COLGROUP_TAG, COL_TAG, TBODY_TAG, THEAD_TAG, TFOOT_TAG, TR_TAG, TD_TAG, TH_TAG, -- Section 4.10 Forms FORM_TAG, LABEL_TAG, INPUT_TAG, BUTTON_TAG, SELECT_TAG, DATALIST_TAG, OPTGROUP_TAG, OPTION_TAG, TEXTAREA_TAG, KEYGEN_TAG, OUTPUT_TAG, PROGRESS_TAG, METER_TAG, FIELDSET_TAG, LEGEND_TAG, -- Section 4.11 Scripting SCRIPT_TAG, NOSCRIPT_TAG, TEMPLATE_TAG, CANVAS_TAG, -- Deprecated tags but still used widely TT_TAG, -- Unknown tags UNKNOWN_TAG ); -- Find the tag from the tag name. function Find_Tag (Name : in Wide_Wide_String) return Html_Tag; type String_Access is access constant String; -- Get the HTML tag name. function Get_Tag_Name (Tag : in Html_Tag) return String_Access; type Tag_Boolean_Array is array (Html_Tag) of Boolean; No_End_Tag : constant Tag_Boolean_Array := ( BASE_TAG => True, LINK_TAG => True, META_TAG => True, IMG_TAG => True, HR_TAG => True, BR_TAG => True, WBR_TAG => True, INPUT_TAG => True, KEYGEN_TAG => True, others => False); Tag_Omission : constant Tag_Boolean_Array := ( -- Section 4.4 Grouping content LI_TAG => True, DT_TAG => True, DD_TAG => True, -- Section 4.5 Text-level semantics RB_TAG => True, RT_TAG => True, RTC_TAG => True, RP_TAG => True, -- Section 4.9 Tabular data TH_TAG => True, TD_TAG => True, TR_TAG => True, TBODY_TAG => True, THEAD_TAG => True, TFOOT_TAG => True, OPTGROUP_TAG => True, OPTION_TAG => True, others => False); end Wiki;
Add STRONG and EMPHASIS formats
Add STRONG and EMPHASIS formats
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2a16911023bc3a6287d004ca2ca5d973e537128a
src/asf-components-widgets-panels.adb
src/asf-components-widgets-panels.adb
----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; package body ASF.Components.Widgets.Panels is -- ------------------------------ -- Render the panel header. -- ------------------------------ procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Header : Util.Beans.Objects.Object; Header_Facet : ASF.Components.Base.UIComponent_Access; begin Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-header"); Header := UI.Get_Attribute (Name => HEADER_ATTR_NAME, Context => Context); if not Util.Beans.Objects.Is_Empty (Header) then Writer.Start_Element ("span"); Writer.Write_Text (Header); Writer.End_Element ("span"); Writer.End_Element ("div"); end if; -- If there is a header facet, render it now. Header_Facet := UI.Get_Facet (HEADER_FACET_NAME); if Header_Facet /= null then Header_Facet.Encode_All (Context); end if; Writer.End_Element ("div"); null; end Render_Header; -- ------------------------------ -- Render the panel footer. -- ------------------------------ procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Footer : Util.Beans.Objects.Object; Footer_Facet : ASF.Components.Base.UIComponent_Access; Has_Footer : Boolean; begin Footer_Facet := UI.Get_Facet (FOOTER_FACET_NAME); Footer := UI.Get_Attribute (Name => FOOTER_ATTR_NAME, Context => Context); Has_Footer := Footer_Facet /= null or else not Util.Beans.Objects.Is_Empty (Footer); if Has_Footer then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-footer"); end if; if not Util.Beans.Objects.Is_Empty (Footer) then Writer.Write_Text (Footer); end if; -- If there is a footer facet, render it now. if Footer_Facet /= null then Footer_Facet.Encode_All (Context); end if; if Has_Footer then Writer.End_Element ("div"); end if; end Render_Footer; -- ------------------------------ -- Render the panel header and prepare for the panel content. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel"); UIPanel'Class (UI).Render_Header (Writer.all, Context); Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-content"); end if; end Encode_Begin; -- ------------------------------ -- Render the panel footer. -- ------------------------------ overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); UIPanel'Class (UI).Render_Footer (Writer.all, Context); Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Panels;
----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; package body ASF.Components.Widgets.Panels is -- ------------------------------ -- Render the panel header. -- ------------------------------ procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Header : Util.Beans.Objects.Object; Header_Facet : ASF.Components.Base.UIComponent_Access; begin Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-header ui-widget-header"); Header := UI.Get_Attribute (Name => HEADER_ATTR_NAME, Context => Context); if not Util.Beans.Objects.Is_Empty (Header) then Writer.Start_Element ("span"); Writer.Write_Text (Header); Writer.End_Element ("span"); Writer.End_Element ("div"); end if; -- If there is a header facet, render it now. Header_Facet := UI.Get_Facet (HEADER_FACET_NAME); if Header_Facet /= null then Header_Facet.Encode_All (Context); end if; Writer.End_Element ("div"); null; end Render_Header; -- ------------------------------ -- Render the panel footer. -- ------------------------------ procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Footer : Util.Beans.Objects.Object; Footer_Facet : ASF.Components.Base.UIComponent_Access; Has_Footer : Boolean; begin Footer_Facet := UI.Get_Facet (FOOTER_FACET_NAME); Footer := UI.Get_Attribute (Name => FOOTER_ATTR_NAME, Context => Context); Has_Footer := Footer_Facet /= null or else not Util.Beans.Objects.Is_Empty (Footer); if Has_Footer then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-footer ui-widget-footer"); end if; if not Util.Beans.Objects.Is_Empty (Footer) then Writer.Write_Text (Footer); end if; -- If there is a footer facet, render it now. if Footer_Facet /= null then Footer_Facet.Encode_All (Context); end if; if Has_Footer then Writer.End_Element ("div"); end if; end Render_Footer; -- ------------------------------ -- Render the panel header and prepare for the panel content. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel ui-widget ui-corner-all"); UIPanel'Class (UI).Render_Header (Writer.all, Context); Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-content ui-widget-content"); end if; end Encode_Begin; -- ------------------------------ -- Render the panel footer. -- ------------------------------ overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); UIPanel'Class (UI).Render_Footer (Writer.all, Context); Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Panels;
Add some CSS from jQuery UI widgets
Add some CSS from jQuery UI widgets
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c926f4de593cfd3a08acc4a879d112fa04c9adc5
awa/plugins/awa-jobs/src/awa-jobs.ads
awa/plugins/awa-jobs/src/awa-jobs.ads
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>AWA.Jobs</b> plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. The `Jobs` plugin is intended to help web application -- designers in implementing end to end asynchronous operation. A client schedules a job -- and does not block nor wait for the immediate completion. Instead, the client asks -- periodically or uses other mechanisms to check for the job completion. -- -- === Writing a job === -- A new job type is created by implementing the `Execute` operation of the abstract -- `Job_Type` tagged record. -- -- type Resize_Job is new AWA.Jobs.Job_Type with ...; -- -- The `Execute` procedure must be implemented. It should use the `Get_Parameter` functions -- to retrieve the job parameters and perform the work. While the job is being executed, -- it can save result by using the `Set_Result` operations, save messages by using the -- `Set_Message` operations and report the progress by using `Set_Progress`. -- It may report the job status by using `Set_Status`. -- -- procedure Execute (Job : in out Resize_Job) is -- begin -- Job.Set_Result ("done", "ok"); -- end Execute; -- -- === Registering a job === -- The <b>AWA.Jobs</b> plugin must be able to create the job instance when it is going to -- be executed. For this, a registration package must be instantiated: -- -- package Resize_Def is new AWA.Jobs.Definition (Resize_Job); -- -- and the job definition must be added: -- -- AWA.Jobs.Modules.Register (Resize_Def.Create'Access); -- -- === Scheduling a job === -- To schedule a job, declare an instance of the job to execute and set the job specific -- parameters. The job parameters will be saved in the database. As soon as parameters -- are defined, call the `Schedule` procedure to schedule the job in the job queue and -- obtain a job identifier. -- -- Resize : Resize_Job; -- ... -- Resize.Set_Parameter ("file", "image.png"); -- Resize.Set_Parameter ("width", "32"); -- Resize.Set_Parameter ("height, "32"); -- Resize.Schedule; -- -- === Checking for job completion === -- -- -- == Data Model == -- @include jobs.hbm.xml -- package AWA.Jobs is end AWA.Jobs;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>AWA.Jobs</b> plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. The `Jobs` plugin is intended to help web application -- designers in implementing end to end asynchronous operation. A client schedules a job -- and does not block nor wait for the immediate completion. Instead, the client asks -- periodically or uses other mechanisms to check for the job completion. -- -- === Writing a job === -- A new job type is created by implementing the `Execute` operation of the abstract -- `Job_Type` tagged record. -- -- type Resize_Job is new AWA.Jobs.Job_Type with ...; -- -- The `Execute` procedure must be implemented. It should use the `Get_Parameter` functions -- to retrieve the job parameters and perform the work. While the job is being executed, -- it can save result by using the `Set_Result` operations, save messages by using the -- `Set_Message` operations and report the progress by using `Set_Progress`. -- It may report the job status by using `Set_Status`. -- -- procedure Execute (Job : in out Resize_Job) is -- begin -- Job.Set_Result ("done", "ok"); -- end Execute; -- -- === Registering a job === -- The <b>AWA.Jobs</b> plugin must be able to create the job instance when it is going to -- be executed. For this, a registration package must be instantiated: -- -- package Resize_Def is new AWA.Jobs.Definition (Resize_Job); -- -- and the job definition must be added: -- -- AWA.Jobs.Modules.Register (Resize_Def.Create'Access); -- -- === Scheduling a job === -- To schedule a job, declare an instance of the job to execute and set the job specific -- parameters. The job parameters will be saved in the database. As soon as parameters -- are defined, call the `Schedule` procedure to schedule the job in the job queue and -- obtain a job identifier. -- -- Resize : Resize_Job; -- ... -- Resize.Set_Parameter ("file", "image.png"); -- Resize.Set_Parameter ("width", "32"); -- Resize.Set_Parameter ("height, "32"); -- Resize.Schedule; -- -- === Checking for job completion === -- -- -- @include awa-jobs-modules.ads -- -- == Data Model == -- @include jobs.hbm.xml -- package AWA.Jobs is end AWA.Jobs;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
6a1421ab334d83d744519dce5590440a211d3bfd
awa/src/awa-permissions.adb
awa/src/awa-permissions.adb
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Perm.Entity := Entity; if not (Security.Contexts.Has_Permission (Perm)) then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); 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>, <entity-type>, <sql> and -- <entity-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 AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Entity = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entity => Into.Entity); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entity := 0; end; 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>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String is begin return NAME; end Get_Name; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) 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.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); Result : Boolean; begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Perm.Entity := Entity; Context.Has_Permission (Perm, Result); if not Result then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); 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>, <entity-type>, <sql> and -- <entity-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 AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Entity = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entity => Into.Entity); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entity := 0; end; 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>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String is begin return NAME; end Get_Name; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) 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.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. overriding procedure Finish_Config (Into : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is begin null; end Finish_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
Fix Check_Permission
Fix Check_Permission
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2fd92bb615198880189f35cc5250d11d8002ef20
src/gen-artifacts-docs-markdown.adb
src/gen-artifacts-docs-markdown.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015, 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.Fixed; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Return True if the link has either a http:// or a https:// scheme. -- ------------------------------ function Has_Scheme (Link : in String) return Boolean is begin if Link'Length < 8 then return False; elsif Link (Link'First .. Link'First + 6) = "http://" then return True; elsif Link (Link'First .. Link'First + 7) = "https://" then return True; else return False; end if; end Has_Scheme; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; -- ------------------------------ -- Write a line doing some link transformation for Markdown. -- ------------------------------ procedure Write_Text (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is pragma Unreferenced (Formatter); Pos : Natural; Start : Natural := Text'First; End_Pos : Natural; Last_Pos : Natural; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Ada.Text_IO.Put (File, Text (Start .. Text'Last)); return; end if; Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); -- Parse a markdown link format. if Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; else Pos := Pos + 1; End_Pos := Pos; while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop End_Pos := End_Pos + 1; end loop; Last_Pos := End_Pos; while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop Last_Pos := Last_Pos + 1; end loop; if Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "("); Ada.Text_IO.Put (File, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "[["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "|"); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]"); end if; Start := Last_Pos + 1; end if; end loop; end Write_Text; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; if Formatter.Mode = L_START_CODE and then Line'Length > 2 and then Line (Line'First .. Line'First + 1) = " " then Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last)); elsif Formatter.Mode = L_TEXT then Formatter.Write_Text (File, Line); Ada.Text_IO.New_Line (File); else Ada.Text_IO.Put_Line (File, Line); end if; end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; Formatter.Mode := Line.Kind; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "```"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "# " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_2 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "## " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_3 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "### " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_4 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "#### " & Line.Content); Formatter.Mode := L_TEXT; when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end if; end Finish_Document; end Gen.Artifacts.Docs.Markdown;
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Util.Strings; with Util.Log.Loggers; package body Gen.Artifacts.Docs.Markdown is function Has_Scheme (Link : in String) return Boolean; function Is_Image (Link : in String) return Boolean; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Docs.Mark"); -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is pragma Unreferenced (Formatter); begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is pragma Unreferenced (Formatter); begin if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "# " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end if; end Start_Document; -- ------------------------------ -- Return True if the link has either a http:// or a https:// scheme. -- ------------------------------ function Has_Scheme (Link : in String) return Boolean is begin if Link'Length < 8 then return False; elsif Link (Link'First .. Link'First + 6) = "http://" then return True; elsif Link (Link'First .. Link'First + 7) = "https://" then return True; else return False; end if; end Has_Scheme; function Is_Image (Link : in String) return Boolean is begin if Link'Length < 4 then return False; elsif Link (Link'Last - 3 .. Link'Last) = ".png" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".jpg" then return True; elsif Link (Link'Last - 3 .. Link'Last) = ".gif" then return True; else Log.Info ("Link {0} not an image", Link); return False; end if; end Is_Image; -- ------------------------------ -- Write a line doing some link transformation for Markdown. -- ------------------------------ procedure Write_Text (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Text : in String) is pragma Unreferenced (Formatter); Pos : Natural; Start : Natural := Text'First; End_Pos : Natural; Last_Pos : Natural; begin -- Transform links -- [Link] -> [[Link]] -- [Link Title] -> [[Title|Link]] -- -- Do not change the following links: -- [[Link|Title]] loop Pos := Util.Strings.Index (Text, '[', Start); if Pos = 0 or else Pos = Text'Last then Ada.Text_IO.Put (File, Text (Start .. Text'Last)); return; end if; Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); -- Parse a markdown link format. if Text (Pos + 1) = '[' then Start := Pos + 2; Pos := Util.Strings.Index (Text, ']', Pos + 2); if Pos = 0 then if Is_Image (Text (Start .. Text'Last)) then Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); else Ada.Text_IO.Put (File, Text (Start - 2 .. Text'Last)); end if; return; end if; if Is_Image (Text (Start .. Pos - 1)) then Ada.Text_IO.Put (File, "![]("); Ada.Text_IO.Put (File, Text (Start .. Pos - 1)); Ada.Text_IO.Put (File, ")"); Start := Pos + 2; else Ada.Text_IO.Put (File, Text (Start .. Pos)); Start := Pos + 1; end if; else Pos := Pos + 1; End_Pos := Pos; while End_Pos < Text'Last and Text (End_Pos) /= ' ' and Text (End_Pos) /= ']' loop End_Pos := End_Pos + 1; end loop; Last_Pos := End_Pos; while Last_Pos < Text'Last and Text (Last_Pos) /= ']' loop Last_Pos := Last_Pos + 1; end loop; if Is_Image (Text (Pos .. Last_Pos - 1)) then Ada.Text_IO.Put (File, "!["); -- Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. Last_Pos - 1)); Ada.Text_IO.Put (File, ")"); elsif Is_Image (Text (Pos .. End_Pos)) then Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "!["); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]("); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, ")"); elsif Has_Scheme (Text (Pos .. End_Pos)) then Ada.Text_IO.Put (File, "["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "("); Ada.Text_IO.Put (File, Ada.Strings.Fixed.Trim (Text (Pos .. End_Pos), Ada.Strings.Both)); Ada.Text_IO.Put (File, ")"); else Last_Pos := Last_Pos - 1; Ada.Text_IO.Put (File, "[["); Ada.Text_IO.Put (File, Text (End_Pos + 1 .. Last_Pos)); Ada.Text_IO.Put (File, "|"); Ada.Text_IO.Put (File, Text (Pos .. End_Pos)); Ada.Text_IO.Put (File, "]"); end if; Start := Last_Pos + 1; end if; end loop; end Write_Text; -- ------------------------------ -- Write a line in the document. -- ------------------------------ procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String) is begin if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; if Formatter.Mode = L_START_CODE and then Line'Length > 2 and then Line (Line'First .. Line'First + 1) = " " then Ada.Text_IO.Put_Line (File, Line (Line'First + 2 .. Line'Last)); elsif Formatter.Mode = L_TEXT then Formatter.Write_Text (File, Line); Ada.Text_IO.New_Line (File); else Ada.Text_IO.Put_Line (File, Line); end if; end Write_Line; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin case Line.Kind is when L_LIST => Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; Formatter.Mode := Line.Kind; when L_LIST_ITEM => Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; when L_START_CODE => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "```Ada"); when L_END_CODE => Formatter.Mode := L_TEXT; Formatter.Write_Line (File, "```"); when L_TEXT => Formatter.Write_Line (File, Line.Content); when L_HEADER_1 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "# " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_2 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "## " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_3 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "### " & Line.Content); Formatter.Mode := L_TEXT; when L_HEADER_4 => Formatter.Mode := Line.Kind; Formatter.Write_Line (File, "#### " & Line.Content); Formatter.Mode := L_TEXT; when others => null; end case; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is pragma Unreferenced (Formatter); begin Ada.Text_IO.New_Line (File); if Document.Print_Footer then Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from *" & Source & "*"); end if; end Finish_Document; end Gen.Artifacts.Docs.Markdown;
Fix formatting of code block to tell the language is Ada
Fix formatting of code block to tell the language is Ada
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
9757b13c42b1b0df94a7e8609023ee897f863764
src/util-streams-buffered.ads
src/util-streams-buffered.ads
----------------------------------------------------------------------- -- Util.Streams.Buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; package Util.Streams.Buffered is pragma Preelaborate; -- ----------------------- -- Buffered stream -- ----------------------- -- The <b>Buffered_Stream</b> is an output/input stream which uses -- an intermediate buffer. It can be configured to read or write to -- another stream that it will read or write using the buffer. -- -- It is necessary to call <b>Flush</b> to make sure the data -- is written to the target stream. The <b>Flush</b> operation will -- be called when finalizing the buffered stream. type Buffered_Stream is limited new Output_Stream and Input_Stream with private; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive); -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Buffered_Stream; Content : in String); -- Close the sink. overriding procedure Close (Stream : in out Buffered_Stream); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access; -- Write a raw character on the stream. procedure Write (Stream : in out Buffered_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Buffered_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Buffered_Stream; Item : in String); -- Write a raw string on the stream. procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write (Stream : in out Buffered_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Buffered_Stream); -- Get the number of element in the stream. function Get_Size (Stream : in Buffered_Stream) return Natural; -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Buffered_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Buffered_Stream; Char : out Character); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Buffered_Stream) return Boolean; private use Ada.Streams; type Buffered_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The output stream to use for flushing the buffer. Output : Output_Stream_Access := null; -- The input stream to use to fill the buffer. Input : Input_Stream_Access := null; No_Flush : Boolean := False; -- Reached end of file when reading. Eof : Boolean := False; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Buffered_Stream); end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams Stream utilities -- Copyright (C) 2010, 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 Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; package Util.Streams.Buffered is pragma Preelaborate; -- ----------------------- -- Buffered stream -- ----------------------- -- The <b>Buffered_Stream</b> is an output/input stream which uses -- an intermediate buffer. It can be configured to read or write to -- another stream that it will read or write using the buffer. -- -- It is necessary to call <b>Flush</b> to make sure the data -- is written to the target stream. The <b>Flush</b> operation will -- be called when finalizing the buffered stream. type Buffered_Stream is limited new Output_Stream and Input_Stream with private; type Buffer_Access is access Ada.Streams.Stream_Element_Array; -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Buffered_Stream; Output : in Output_Stream_Access; Input : in Input_Stream_Access; Size : in Positive); -- Initialize the stream with a buffer of <b>Size</b> bytes. procedure Initialize (Stream : in out Buffered_Stream; Size : in Positive); -- Initialize the stream to read from the string. procedure Initialize (Stream : in out Buffered_Stream; Content : in String); -- Close the sink. overriding procedure Close (Stream : in out Buffered_Stream); -- Get the direct access to the buffer. function Get_Buffer (Stream : in Buffered_Stream) return Buffer_Access; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Buffered_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Buffered_Stream); -- Get the number of element in the stream. function Get_Size (Stream : in Buffered_Stream) return Natural; -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; procedure Fill (Stream : in out Buffered_Stream); -- Read one character from the input stream. procedure Read (Stream : in out Buffered_Stream; Char : out Character); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Buffered_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Buffered_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String); -- Returns True if the end of the stream is reached. function Is_Eof (Stream : in Buffered_Stream) return Boolean; private use Ada.Streams; type Buffered_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record -- The buffer where the data is written before being flushed. Buffer : Buffer_Access := null; -- The next write position within the buffer. Write_Pos : Stream_Element_Offset := 0; -- The next read position within the buffer. Read_Pos : Stream_Element_Offset := 1; -- The last valid write position within the buffer. Last : Stream_Element_Offset := 0; -- The output stream to use for flushing the buffer. Output : Output_Stream_Access := null; -- The input stream to use to fill the buffer. Input : Input_Stream_Access := null; No_Flush : Boolean := False; -- Reached end of file when reading. Eof : Boolean := False; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Buffered_Stream); end Util.Streams.Buffered;
Refactor Buffered_Stream and Print_Stream - move character related Write operation to the Texts package (Print_Stream)
Refactor Buffered_Stream and Print_Stream - move character related Write operation to the Texts package (Print_Stream)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5478c750d5fd58c1632c8ff600208e42a3cd6b26
src/util-serialize-mappers-vector_mapper.adb
src/util-serialize-mappers-vector_mapper.adb
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Vector_Mapper -- Mapper for vector types -- 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.Log.Loggers; package body Util.Serialize.Mappers.Vector_Mapper is use Vectors; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers.Vector_Mapper", Util.Log.WARN_LEVEL); Key : Util.Serialize.Contexts.Data_Key; -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. -- ----------------------- -- Get the vector object. -- ----------------------- function Get_Vector (Data : in Vector_Data) return Vector_Type_Access is begin return Data.Vector; end Get_Vector; -- ----------------------- -- Set the vector object. -- ----------------------- procedure Set_Vector (Data : in out Vector_Data; Vector : in Vector_Type_Access) is begin Data.Vector := Vector; end Set_Vector; -- ----------------------- -- Record mapper -- ----------------------- -- ----------------------- -- Set the <b>Data</b> vector in the context. -- ----------------------- procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Data : in Vector_Type_Access) is Data_Context : Vector_Data_Access := new Vector_Data; begin Data_Context.Vector := Data; Data_Context.Position := Index_Type'First; Ctx.Set_Data (Key => Key, Content => Data_Context.all'Unchecked_Access); end Set_Context; -- ----------------------- -- 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 pragma Unreferenced (Handler); procedure Process (Element : in out Element_Type); procedure Process (Element : in out Element_Type) is begin Element_Mapper.Set_Member (Map, Element, Value); end Process; D : constant Contexts.Data_Access := Ctx.Get_Data (Key); begin Log.Debug ("Updating vector element"); if not (D.all in Vector_Data'Class) then raise Util.Serialize.Contexts.No_Data; end if; declare DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access; begin if DE.Vector = null then raise Util.Serialize.Contexts.No_Data; end if; -- Update the element through the generic procedure Update_Element (DE.Vector.all, DE.Position - 1, Process'Access); end; end Execute; procedure Set_Mapping (Into : in out Mapper; Inner : in Element_Mapper.Mapper_Access) is begin Into.Mapper := Inner.all'Unchecked_Access; Into.Map.Bind (Inner); end Set_Mapping; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String) return Util.Serialize.Mappers.Mapper_Access is begin return Controller.Mapper.Find_Mapper (Name); end Find_Mapper; overriding procedure Initialize (Controller : in out Mapper) is begin Controller.Mapper := Controller.Map'Unchecked_Access; end Initialize; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is pragma Unreferenced (Handler); procedure Set_Context (Item : in out Element_Type); D : constant Contexts.Data_Access := Context.Get_Data (Key); procedure Set_Context (Item : in out Element_Type) is begin Element_Mapper.Set_Context (Ctx => Context, Element => Item'Unrestricted_Access); end Set_Context; begin Log.Debug ("Creating vector element {0}", Name); if not (D.all in Vector_Data'Class) then raise Util.Serialize.Contexts.No_Data; end if; declare DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access; begin if DE.Vector = null then raise Util.Serialize.Contexts.No_Data; end if; Insert_Space (DE.Vector.all, DE.Position); DE.Vector.Update_Element (Index => DE.Position, Process => Set_Context'Access); DE.Position := DE.Position + 1; end; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin null; end Finish_Object; -- ----------------------- -- Write the element on the stream using the mapper description. -- ----------------------- procedure Write (Handler : in Mapper; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Vectors.Vector) is Pos : Vectors.Cursor := Element.First; begin Stream.Start_Array (Element.Length); while Vectors.Has_Element (Pos) loop Element_Mapper.Write (Handler.Mapper.all, Handler.Map.Get_Getter, Stream, Vectors.Element (Pos)); Vectors.Next (Pos); end loop; Stream.End_Array; end Write; begin -- Allocate the unique data key. Util.Serialize.Contexts.Allocate (Key); end Util.Serialize.Mappers.Vector_Mapper;
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Vector_Mapper -- Mapper for vector types -- Copyright (C) 2010, 2011, 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; package body Util.Serialize.Mappers.Vector_Mapper is use Vectors; use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers.Vector_Mapper", Util.Log.WARN_LEVEL); Key : Util.Serialize.Contexts.Data_Key; -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. -- ----------------------- -- Get the vector object. -- ----------------------- function Get_Vector (Data : in Vector_Data) return Vector_Type_Access is begin return Data.Vector; end Get_Vector; -- ----------------------- -- Set the vector object. -- ----------------------- procedure Set_Vector (Data : in out Vector_Data; Vector : in Vector_Type_Access) is begin Data.Vector := Vector; end Set_Vector; -- ----------------------- -- Record mapper -- ----------------------- -- ----------------------- -- Set the <b>Data</b> vector in the context. -- ----------------------- procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Data : in Vector_Type_Access) is Data_Context : constant Vector_Data_Access := new Vector_Data; begin Data_Context.Vector := Data; Data_Context.Position := Index_Type'First; Ctx.Set_Data (Key => Key, Content => Data_Context.all'Unchecked_Access); end Set_Context; -- ----------------------- -- 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 pragma Unreferenced (Handler); procedure Process (Element : in out Element_Type); procedure Process (Element : in out Element_Type) is begin Element_Mapper.Set_Member (Map, Element, Value); end Process; D : constant Contexts.Data_Access := Ctx.Get_Data (Key); begin Log.Debug ("Updating vector element"); if not (D.all in Vector_Data'Class) then raise Util.Serialize.Contexts.No_Data; end if; declare DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access; begin if DE.Vector = null then raise Util.Serialize.Contexts.No_Data; end if; -- Update the element through the generic procedure Update_Element (DE.Vector.all, DE.Position - 1, Process'Access); end; end Execute; procedure Set_Mapping (Into : in out Mapper; Inner : in Element_Mapper.Mapper_Access) is begin Into.Mapper := Inner.all'Unchecked_Access; Into.Map.Bind (Inner); end Set_Mapping; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String) return Util.Serialize.Mappers.Mapper_Access is begin return Controller.Mapper.Find_Mapper (Name); end Find_Mapper; overriding procedure Initialize (Controller : in out Mapper) is begin Controller.Mapper := Controller.Map'Unchecked_Access; end Initialize; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is pragma Unreferenced (Handler); procedure Set_Context (Item : in out Element_Type); D : constant Contexts.Data_Access := Context.Get_Data (Key); procedure Set_Context (Item : in out Element_Type) is begin Element_Mapper.Set_Context (Ctx => Context, Element => Item'Unrestricted_Access); end Set_Context; begin Log.Debug ("Creating vector element {0}", Name); if not (D.all in Vector_Data'Class) then raise Util.Serialize.Contexts.No_Data; end if; declare DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access; begin if DE.Vector = null then raise Util.Serialize.Contexts.No_Data; end if; Insert_Space (DE.Vector.all, DE.Position); DE.Vector.Update_Element (Index => DE.Position, Process => Set_Context'Access); DE.Position := DE.Position + 1; end; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin null; end Finish_Object; -- ----------------------- -- Write the element on the stream using the mapper description. -- ----------------------- procedure Write (Handler : in Mapper; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Vectors.Vector) is Pos : Vectors.Cursor := Element.First; begin Stream.Start_Array (Element.Length); while Vectors.Has_Element (Pos) loop Element_Mapper.Write (Handler.Mapper.all, Handler.Map.Get_Getter, Stream, Vectors.Element (Pos)); Vectors.Next (Pos); end loop; Stream.End_Array; end Write; begin -- Allocate the unique data key. Util.Serialize.Contexts.Allocate (Key); end Util.Serialize.Mappers.Vector_Mapper;
Fix compilation warning reported by gcc 4.7
Fix compilation warning reported by gcc 4.7
Ada
apache-2.0
flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util
1bfd833fe92bd6ca57058bbba8c5411274c335a8
matp/src/events/mat-events-probes.ads
matp/src/events/mat-events-probes.ads
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames; package MAT.Events.Probes is subtype Probe_Event_Type is MAT.Events.Targets.Probe_Event_Type; ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Probe_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in Probe_Event_Type) is abstract; ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Get the target events. function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access; -- Read a message from the stream. procedure Read_Message (Reader : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is abstract; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (List : in out Reader_List_Type; Manager : in out Probe_Manager_Type'Class) is abstract; private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Targets.Probe_Index_Type; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Probe_Event_Type; Frames : MAT.Frames.Frame_Type; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames; package MAT.Events.Probes is subtype Probe_Event_Type is MAT.Events.Targets.Probe_Event_Type; ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Probe_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in out Probe_Event_Type) is abstract; ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Targets.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Get the target events. function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access; -- Read a message from the stream. procedure Read_Message (Reader : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is abstract; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_Type'Class; -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. procedure Initialize (List : in out Reader_List_Type; Manager : in out Probe_Manager_Type'Class) is abstract; private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Targets.Probe_Index_Type; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Probe_Event_Type; Frames : MAT.Frames.Frame_Type; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
Change the Event parameter of Execute to an in out parameter
Change the Event parameter of Execute to an in out parameter
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1dcfe318f1ec939d6589aa67d8390fb2c02cc766
src/gen-model-enums.adb
src/gen-model-enums.adb
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- 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; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is begin O.Target := O.Type_Name; null; 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.Name := To_Unbounded_String (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.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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT 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 begin O.Target := O.Type_Name; O.Values.Sort; 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.Name := To_Unbounded_String (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.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;
Sort the enum literal values
Sort the enum literal values
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
9286f70ddee07d6f14b71f286147918d0b4b3555
src/asf-components-widgets-likes.adb
src/asf-components-widgets-likes.adb
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; -- GNAT bug, the with clause is necessary to call Get_Global on the application. pragma Warnings (Off, "*is not referenced"); with ASF.Applications.Main; pragma Warnings (On, "*is not referenced"); with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; G_ANNOTATION_ATTR : aliased constant String := "data-annotation"; G_WIDTH_ATTR : aliased constant String := "data-width"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; FACEBOOK_ATTR_NAME : constant Unbounded_String := To_Unbounded_String ("facebook.client_id"); GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWITTER_NAME : aliased constant String := "twitter"; TWITTER_GENERATOR : aliased Twitter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;js.async=true;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId="); declare App_Id : constant Util.Beans.Objects.Object := Context.Get_Application.Get_Global (FACEBOOK_ATTR_NAME, Context.Get_ELContext.all); begin if Util.Beans.Objects.Is_Empty (App_Id) then UI.Log_Error ("The facebook client application id is empty"); UI.Log_Error ("Please, configure the {0} property in the application", To_String (FACEBOOK_ATTR_NAME)); else Writer.Queue_Script (App_Id); end if; end; Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); Style : constant String := UI.Get_Attribute ("style", Context, ""); Class : constant String := UI.Get_Attribute ("styleClass", Context, ""); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Writer.Start_Element ("div"); if Style'Length > 0 then Writer.Write_Attribute ("style", Style); end if; if Class'Length > 0 then Writer.Write_Attribute ("class", Class); end if; Generators (I).Generator.Render_Like (UI, Href, Context); Writer.End_Element ("div"); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Locales; with Util.Beans.Objects; with Util.Strings.Tokenizers; -- GNAT bug, the with clause is necessary to call Get_Global on the application. pragma Warnings (Off, "*is not referenced"); with ASF.Applications.Main; pragma Warnings (On, "*is not referenced"); with ASF.Requests; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Likes is FB_LAYOUT_ATTR : aliased constant String := "data-layout"; FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces"; FB_WIDTH_ATTR : aliased constant String := "data-width"; FB_ACTION_ATTR : aliased constant String := "data-action"; FB_FONT_ATTR : aliased constant String := "data-font"; FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme"; FB_REF_ATTR : aliased constant String := "data-ref"; FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site"; FB_SEND_ATTR : aliased constant String := "data-send"; TW_VIA_ATTR : aliased constant String := "data-via"; TW_COUNT_ATTR : aliased constant String := "data-count"; TW_SIZE_ATTR : aliased constant String := "data-size"; G_ANNOTATION_ATTR : aliased constant String := "data-annotation"; G_WIDTH_ATTR : aliased constant String := "data-width"; FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script"; GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script"; TWITTER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; TWITTER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.twitter.script"; type Like_Generator_Binding is record Name : Util.Strings.Name_Access; Generator : Like_Generator_Access; end record; type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding; FB_NAME : aliased constant String := "facebook"; FB_GENERATOR : aliased Facebook_Like_Generator; G_NAME : aliased constant String := "google+"; G_GENERATOR : aliased Google_Like_Generator; TWITTER_NAME : aliased constant String := "twitter"; TWITTER_GENERATOR : aliased Twitter_Like_Generator; Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access), 2 => (G_NAME'Access, G_GENERATOR'Access), 3 => (TWITTER_NAME'Access, TWITTER_GENERATOR'Access), others => (null, null)); -- ------------------------------ -- Render the facebook like button according to the component attributes. -- ------------------------------ overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];" & "if (d.getElementById(id)) return;" & "js = d.createElement(s); js.id = id;js.async=true;" & "js.src = ""//connect.facebook.net/"); Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale)); Writer.Queue_Script ("/all.js#xfbml=1&;appId="); declare App_Id : constant String := Context.Get_Application.Get_Config (P_Facebook_App_Id.P); begin if App_Id'Length = 0 then UI.Log_Error ("The facebook client application id is empty"); UI.Log_Error ("Please, configure the '{0}' property " & "in the application", P_Facebook_App_Id.PARAM_NAME); else Writer.Queue_Script (App_Id); end if; end; Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);" & "}(document, 'script', 'facebook-jssdk'));"); Writer.Start_Element ("div"); Writer.Write_Attribute ("id", "fb-root"); Writer.End_Element ("div"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "fb-like"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Google like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js"); end if; Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "g-plusone"); Writer.Write_Attribute ("data-href", Href); UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer); Writer.End_Element ("div"); end Render_Like; -- ------------------------------ -- Tweeter like generator -- ------------------------------ overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (Generator); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Request : constant ASF.Requests.Request_Access := Context.Get_Request; Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale); begin if not Context.Is_Ajax_Request and then Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWITTER_SCRIPT_ATTRIBUTE)) then Request.Set_Attribute (TWITTER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True)); Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0]," & "p=/^http:/.test(d.location)?'http':'https';" & "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;" & "js.src=p+'://platform.twitter.com/widgets.js';" & "fjs.parentNode.insertBefore(js,fjs);}}" & "(document, 'script', 'twitter-wjs');"); end if; Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "https://twitter.com/share"); Writer.Write_Attribute ("class", "twitter-share-button"); Writer.Write_Attribute ("data-url", Href); Writer.Write_Attribute ("data-lang", Lang); UI.Render_Attributes (Context, TWITTER_ATTRIBUTE_NAMES, Writer); Writer.Write_Text ("Tweet"); Writer.End_Element ("a"); end Render_Like; -- ------------------------------ -- Get the link to submit in the like action. -- ------------------------------ function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is Href : constant String := UI.Get_Attribute ("href", Context, ""); begin if Href'Length > 0 then return Href; else return Context.Get_Request.Get_Request_URI; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; Kind : constant String := UI.Get_Attribute ("type", Context, ""); Href : constant String := UILike'Class (UI).Get_Link (Context); Style : constant String := UI.Get_Attribute ("style", Context, ""); Class : constant String := UI.Get_Attribute ("styleClass", Context, ""); procedure Render (Name : in String; Done : out Boolean); procedure Render (Name : in String; Done : out Boolean) is use type Util.Strings.Name_Access; begin Done := False; for I in Generators'Range loop exit when Generators (I).Name = null; if Generators (I).Name.all = Name then Writer.Start_Element ("div"); if Style'Length > 0 then Writer.Write_Attribute ("style", Style); end if; if Class'Length > 0 then Writer.Write_Attribute ("class", Class); end if; Generators (I).Generator.Render_Like (UI, Href, Context); Writer.End_Element ("div"); return; end if; end loop; UI.Log_Error ("Like type {0} is not recognized", Name); end Render; begin if Kind'Length = 0 then UI.Log_Error ("The like type is empty."); else Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",", Process => Render'Access); end if; end; end if; end Encode_Begin; -- ------------------------------ -- Register the like generator under the given name. -- ------------------------------ procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access) is use type Util.Strings.Name_Access; begin for I in Generators'Range loop if Generators (I).Name = null then Generators (I).Name := Name; Generators (I).Generator := Generator; return; end if; end loop; end Register_Like; begin FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access); FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access); TWITTER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access); GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access); end ASF.Components.Widgets.Likes;
Use the application configuration parameter to retrieve the Facebook application client ID
Use the application configuration parameter to retrieve the Facebook application client ID
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
eea195c472c44c2560b28b1cf9c72597829580a6
mat/src/mat-readers.adb
mat/src/mat-readers.adb
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Events; with MAT.Types; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers"); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Message_Handler; begin Handler.For_Servant := Reader; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Readers.Insert (Name, Handler); end Register_Reader; procedure Read_Probe (Client : in out Manager_Base; Msg : in out Message) is use type Interfaces.Unsigned_64; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : access MAT.Events.Frame_Info := Client.Frame; begin Frame.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_THREAD_ID => Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind)); when P_FRAME_PC => for I in 1 .. Natural (Count) loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); end if; end loop; when others => null; end case; end; end loop; Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32); Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec); end Read_Probe; procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message) is use type MAT.Events.Attribute_Table_Ptr; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Message_Handler := Handler_Maps.Element (Pos); begin Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name); Frame : Message_Handler; procedure Add_Handler (Key : in String; Element : in out Message_Handler) is begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0}", Name); if Name = "begin" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Message_Handler) is use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("begin", Frame); end if; end; end loop; if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. -- ------------------------------ procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message) is Count : MAT.Types.Uint16; begin Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; Client.Frame := new MAT.Events.Frame_Info (512); exception when E : others => Log.Error ("Exception while reading headers ", E); end Read_Headers; end MAT.Readers;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Events; with MAT.Types; with MAT.Readers.Marshaller; with Interfaces; package body MAT.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers"); P_TIME_SEC : constant MAT.Events.Internal_Reference := 0; P_TIME_USEC : constant MAT.Events.Internal_Reference := 1; P_THREAD_ID : constant MAT.Events.Internal_Reference := 2; P_THREAD_SP : constant MAT.Events.Internal_Reference := 3; P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4; P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5; P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6; P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7; P_FRAME : constant MAT.Events.Internal_Reference := 8; P_FRAME_PC : constant MAT.Events.Internal_Reference := 9; TIME_SEC_NAME : aliased constant String := "time-sec"; TIME_USEC_NAME : aliased constant String := "time-usec"; THREAD_ID_NAME : aliased constant String := "thread-id"; THREAD_SP_NAME : aliased constant String := "thread-sp"; RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt"; RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt"; RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw"; RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw"; FRAME_NAME : aliased constant String := "frame"; FRAME_PC_NAME : aliased constant String := "frame-pc"; Probe_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => TIME_SEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_SEC), 2 => (Name => TIME_USEC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_TIME_USEC), 3 => (Name => THREAD_ID_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_ID), 4 => (Name => THREAD_SP_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_THREAD_SP), 5 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME), 6 => (Name => FRAME_PC_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => P_FRAME_PC) ); function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (Key); end Hash; -- ------------------------------ -- Register the reader to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. -- ------------------------------ procedure Register_Reader (Into : in out Manager_Base; Reader : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Const_Attribute_Table_Access) is Handler : Message_Handler; begin Handler.For_Servant := Reader; Handler.Id := Id; Handler.Attributes := Model; Handler.Mapping := null; Into.Readers.Insert (Name, Handler); end Register_Reader; procedure Read_Probe (Client : in out Manager_Base; Msg : in out Message) is use type Interfaces.Unsigned_64; Count : Natural := 0; Time_Sec : MAT.Types.Uint32 := 0; Time_Usec : MAT.Types.Uint32 := 0; Frame : access MAT.Events.Frame_Info := Client.Frame; begin Frame.Thread := 0; Frame.Stack := 0; Frame.Cur_Depth := 0; for I in Client.Probe'Range loop declare Def : MAT.Events.Attribute renames Client.Probe (I); begin case Def.Ref is when P_TIME_SEC => Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_TIME_USEC => Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_THREAD_ID => Frame.Thread := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind); when P_THREAD_SP => Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when P_FRAME => Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg.Buffer, Def.Kind)); when P_FRAME_PC => for I in 1 .. Natural (Count) loop if Count < Frame.Depth then Frame.Frame (I) := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); end if; end loop; when others => null; end case; end; end loop; Frame.Time := Interfaces.Shift_Left (Interfaces.Unsigned_64 (Time_Sec), 32); Frame.Time := Frame.Time or Interfaces.Unsigned_64 (Time_Usec); end Read_Probe; procedure Dispatch_Message (Client : in out Manager_Base; Msg : in out Message) is use type MAT.Events.Attribute_Table_Ptr; Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event); begin Log.Debug ("Dispatch message {0} - size {1}", MAT.Types.Uint16'Image (Event), Natural'Image (Msg.Size)); if not Handler_Maps.Has_Element (Pos) then -- Message is not handled, skip it. null; else if Client.Probe /= null then Read_Probe (Client, Msg); end if; declare Handler : constant Message_Handler := Handler_Maps.Element (Pos); begin Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Client.Frame.all, Msg); end; end if; exception when E : others => Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E); end Dispatch_Message; -- ------------------------------ -- Read an event definition from the stream and configure the reader. -- ------------------------------ procedure Read_Definition (Client : in out Manager_Base; Msg : in out Message) is Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name); Frame : Message_Handler; procedure Add_Handler (Key : in String; Element : in out Message_Handler) is begin Client.Handlers.Insert (Event, Element); end Add_Handler; begin Log.Debug ("Read event definition {0}", Name); if Name = "begin" then Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); Frame.Attributes := Probe_Attributes'Access; Client.Probe := Frame.Mapping; else Frame.Mapping := null; end if; for I in 1 .. Natural (Count) loop declare Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer); Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); procedure Read_Attribute (Key : in String; Element : in out Message_Handler) is use type MAT.Events.Attribute_Table_Ptr; begin if Element.Mapping = null then Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count)); end if; for J in Element.Attributes'Range loop if Element.Attributes (J).Name.all = Name then Element.Mapping (I) := Element.Attributes (J); if Size = 1 then Element.Mapping (I).Kind := MAT.Events.T_UINT8; elsif Size = 2 then Element.Mapping (I).Kind := MAT.Events.T_UINT16; elsif Size = 4 then Element.Mapping (I).Kind := MAT.Events.T_UINT32; elsif Size = 8 then Element.Mapping (I).Kind := MAT.Events.T_UINT64; else Element.Mapping (I).Kind := MAT.Events.T_UINT32; end if; end if; end loop; end Read_Attribute; use type MAT.Events.Attribute_Table_Ptr; begin if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Read_Attribute'Access); end if; if Frame.Mapping /= null then Read_Attribute ("begin", Frame); end if; end; end loop; if Reader_Maps.Has_Element (Pos) then Client.Readers.Update_Element (Pos, Add_Handler'Access); end if; end Read_Definition; -- ------------------------------ -- Read the event data stream headers with the event description. -- Configure the reader to analyze the data stream according to the event descriptions. -- ------------------------------ procedure Read_Headers (Client : in out Manager_Base; Msg : in out Message) is Count : MAT.Types.Uint16; begin Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer); Log.Info ("Read event stream version {0} with {1} definitions", MAT.Types.Uint16'Image (Client.Version), MAT.Types.Uint16'Image (Count)); for I in 1 .. Count loop Read_Definition (Client, Msg); end loop; Client.Frame := new MAT.Events.Frame_Info (512); exception when E : others => Log.Error ("Exception while reading headers ", E); end Read_Headers; end MAT.Readers;
Add the frame info in the Dispatch operation
Add the frame info in the Dispatch operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
8b6ec01196e17a673c19ee37414728a8f5f38e43
src/security-policies-roles.ads
src/security-policies-roles.ads
----------------------------------------------------------------------- -- 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 Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The <tt>Security.Policies.Roles</tt> package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the <tt>Role_Policy</tt> must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt> -- It defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a <tt>Role_Type</tt>. To provide an efficient implementation, the <tt>Role_Type</tt> -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A <tt>Security_Context</tt> must be associated with a set of roles before checking the -- permission. This is done by using the <tt>Set_Role_Context</tt> operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access; -- 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); -- Get the number of roles set in the map. function Get_Count (Map : in Role_Map) return Natural; -- Return the list of role names separated by ','. function To_String (List : in Role_Name_Array) return String; -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Get the list of role names that are defined by the role map. function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Mapper : in out Util.Serialize.Mappers.Processing); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Map_Name_Array := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
----------------------------------------------------------------------- -- security-policies-roles -- Role based policies -- Copyright (C) 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; -- == Role Based Security Policy == -- The `Security.Policies.Roles` package implements a role based security policy. -- In this policy, users are assigned one or several roles and permissions are -- associated with roles. A permission is granted if the user has one of the roles required -- by the permission. -- -- === Policy creation === -- An instance of the `Role_Policy` must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Roles.Role_Policy_Access; -- -- Create the role policy and register it in the policy manager as follows: -- -- Policy := new Role_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- A role is represented by a name in security configuration files. A role based permission -- is associated with a list of roles. The permission is granted if the user has one of these -- roles. When the role based policy is registered in the policy manager, the following -- XML configuration is used: -- -- <policy-rules> -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <security-role> -- <role-name>manager</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- ... -- </policy-rules> -- -- This definition declares two roles: `admin` and `manager` -- It defines a permission `create-workspace` that will be granted if the -- user has either the `admin` or the `manager` role. -- -- Each role is identified by a name in the configuration file. It is represented by -- a `Role_Type`. To provide an efficient implementation, the `Role_Type` -- is represented as an integer with a limit of 64 different roles. -- -- === Assigning roles to users === -- A `Security_Context` must be associated with a set of roles before checking the -- permission. This is done by using the `Set_Role_Context` operation: -- -- Security.Policies.Roles.Set_Role_Context (Security.Contexts.Current, "admin"); -- package Security.Policies.Roles is NAME : constant String := "Role-Policy"; -- Each role is represented by a <b>Role_Type</b> number to provide a fast -- and efficient role check. type Role_Type is new Natural range 0 .. 63; for Role_Type'Size use 8; type Role_Type_Array is array (Positive range <>) of Role_Type; type Role_Name_Array is array (Positive range <>) of Ada.Strings.Unbounded.String_Access; -- 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); -- Get the number of roles set in the map. function Get_Count (Map : in Role_Map) return Natural; -- Return the list of role names separated by ','. function To_String (List : in Role_Name_Array) return String; -- ------------------------------ -- Role principal context -- ------------------------------ -- The <tt>Role_Principal_Context</tt> interface must be implemented by the user -- <tt>Principal</tt> to be able to use the role based policy. The role based policy -- controller will first check that the <tt>Principal</tt> implements that interface. -- It uses the <tt>Get_Roles</tt> function to get the current roles assigned to the user. type Role_Principal_Context is limited interface; function Get_Roles (User : in Role_Principal_Context) return Role_Map is abstract; -- ------------------------------ -- Policy context -- ------------------------------ -- The <b>Role_Policy_Context</b> gives security context information that the role -- based policy can use to verify the permission. type Role_Policy_Context is new Policy_Context with record Roles : Role_Map; end record; type Role_Policy_Context_Access is access all Role_Policy_Context'Class; -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in Role_Map); -- Set the roles which are assigned to the user in the security context. -- The role policy will use these roles to verify a permission. procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class; Roles : in String); -- ------------------------------ -- Role based policy -- ------------------------------ type Role_Policy is new Policy with private; type Role_Policy_Access is access all Role_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in Role_Policy) return String; -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. function Find_Role (Manager : in Role_Policy; Name : in String) return Role_Type; -- Get the role name. function Get_Role_Name (Manager : in Role_Policy; Role : in Role_Type) return String; -- Get the roles that grant the given permission. function Get_Grants (Manager : in Role_Policy; Permission : in Permissions.Permission_Index) return Role_Map; -- Get the list of role names that are defined by the role map. function Get_Role_Names (Manager : in Role_Policy; Map : in Role_Map) return Role_Name_Array; -- Create a role procedure Create_Role (Manager : in out Role_Policy; Name : in String; Role : out Role_Type); -- Get or add a role type for the given name. procedure Add_Role_Type (Manager : in out Role_Policy; Name : in String; Result : out Role_Type); -- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by -- its name and multiple roles are separated by ','. -- Raises Invalid_Name if a role was not found. procedure Set_Roles (Manager : in Role_Policy; Roles : in String; Into : out Role_Map); -- Setup the XML parser to read the <b>role-permission</b> description. overriding procedure Prepare_Config (Policy : in out Role_Policy; Mapper : in out Util.Serialize.Mappers.Processing); -- Finalize the policy manager. overriding procedure Finalize (Policy : in out Role_Policy); -- Get the role policy associated with the given policy manager. -- Returns the role policy instance or null if it was not registered in the policy manager. function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class) return Role_Policy_Access; private -- Array to map a permission index to a list of roles that are granted the permission. type Permission_Role_Array is array (Permission_Index) of Role_Map; type Role_Map_Name_Array is array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access; type Role_Policy is new Policy with record Names : Role_Map_Name_Array := (others => null); Next_Role : Role_Type := Role_Type'First; Name : Util.Beans.Objects.Object; Roles : Role_Type_Array (1 .. Integer (Role_Type'Last)) := (others => 0); Count : Natural := 0; -- The Grants array indicates for each permission the list of roles -- that are granted the permission. This array allows a O(1) lookup. -- The implementation is limited to 256 permissions and 64 roles so this array uses 2K. -- The default is that no role is assigned to the permission. Grants : Permission_Role_Array := (others => (others => False)); end record; end Security.Policies.Roles;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
c89a6dce3c23de7cd1dfbdf4f18f0855d9098efc
src/util-serialize-io-csv.ads
src/util-serialize-io-csv.ads
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with Util.Streams.Texts; -- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files. -- -- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files package Util.Serialize.IO.CSV is type Row_Type is new Natural; type Column_Type is new Positive; -- ------------------------------ -- CSV Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a CSV output stream. -- The stream object takes care of the CSV escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character); -- Enable or disable the double quotes by default for strings. procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean); -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. procedure Write_Cell (Stream : in out Output_Stream; Value : in String); procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer); procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean); procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new row. procedure New_Row (Stream : in out Output_Stream); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write an entity with a null value. procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- ------------------------------ -- CSV Parser -- ------------------------------ -- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly -- in Ada records. type Parser is new Serialize.IO.Parser with private; -- Get the header name for the given column. -- If there was no header line, build a default header for the column. function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String; -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type); -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character); -- Get the field separator. function Get_Field_Separator (Handler : in Parser) return Character; -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character); -- Get the comment separator. Returns ASCII.NUL if comments are not supported. function Get_Comment_Separator (Handler : in Parser) return Character; -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True); -- Parse the stream using the CSV parser. overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class); -- Get the current location (file and line) to report an error message. overriding function Get_Location (Handler : in Parser) return String; private type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Max_Columns : Column_Type := 1; Column : Column_Type := 1; Row : Row_Type := 0; Separator : Character := ','; Quote : Boolean := True; end record; type Parser is new Util.Serialize.IO.Parser with record Has_Header : Boolean := True; Line_Number : Natural := 1; Row : Row_Type := 0; Headers : Util.Strings.Vectors.Vector; Separator : Character := ','; Comment : Character := ASCII.NUL; Use_Default_Headers : Boolean := False; Sink : access Reader'Class; end record; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Vectors; with Util.Streams.Texts; -- The <b>Util.Serialize.IO.CSV</b> package allows to read and write CSV files. -- -- See RFC 4180 - Common Format and MIME Type for Comma-Separated Values (CSV) Files package Util.Serialize.IO.CSV is type Row_Type is new Natural; type Column_Type is new Positive; -- ------------------------------ -- CSV Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a CSV output stream. -- The stream object takes care of the CSV escape rules. type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private; -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character); -- Enable or disable the double quotes by default for strings. procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean); -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. procedure Write_Cell (Stream : in out Output_Stream; Value : in String); procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer); procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean); procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object); -- Start a new row. procedure New_Row (Stream : in out Output_Stream); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String); -- Write the entity value. overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write an entity with a null value. procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- ------------------------------ -- CSV Parser -- ------------------------------ -- The <b>Parser</b> type is a CSV parser which allows to map CVS rows directly -- in Ada records. type Parser is new Serialize.IO.Parser with private; -- Get the header name for the given column. -- If there was no header line, build a default header for the column. function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String; -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type); -- Set the field separator. The default field separator is the comma (','). procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character); -- Get the field separator. function Get_Field_Separator (Handler : in Parser) return Character; -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character); -- Get the comment separator. Returns ASCII.NUL if comments are not supported. function Get_Comment_Separator (Handler : in Parser) return Character; -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True); -- Parse the stream using the CSV parser. overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class); -- Get the current location (file and line) to report an error message. overriding function Get_Location (Handler : in Parser) return String; private type Output_Stream is new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record Max_Columns : Column_Type := 1; Column : Column_Type := 1; Row : Row_Type := 0; Separator : Character := ','; Quote : Boolean := True; end record; type Parser is new Util.Serialize.IO.Parser with record Has_Header : Boolean := True; Line_Number : Natural := 1; Row : Row_Type := 0; Headers : Util.Strings.Vectors.Vector; Separator : Character := ','; Comment : Character := ASCII.NUL; Use_Default_Headers : Boolean := False; Sink : access Reader'Class; end record; end Util.Serialize.IO.CSV;
Use the Input_Buffer_Stream instead of Buffered_Stream
Use the Input_Buffer_Stream instead of Buffered_Stream
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
45bc978a67e4cf8440f92cd2a1de2bde23c1f689
src/base/files/util-files-rolling.adb
src/base/files/util-files-rolling.adb
----------------------------------------------------------------------- -- util-files-rolling -- Rolling file manager -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; with Util.Dates.Simple_Format; package body Util.Files.Rolling is use type Ada.Calendar.Time; use type Ada.Directories.File_Size; -- ------------------------------ -- Format the file pattern with the date and index to produce a file path. -- ------------------------------ function Format (Pattern : in String; Date : in Ada.Calendar.Time; Index : in Natural) return String is Pos : Natural := Pattern'First; Result : Unbounded_String; Info : Util.Dates.Date_Record; First : Natural; begin Util.Dates.Split (Info, Date); while Pos <= Pattern'Last loop if Pattern (Pos) /= '%' or else Pos = Pattern'Last then Ada.Strings.Unbounded.Append (Result, Pattern (Pos)); Pos := Pos + 1; elsif Pattern (Pos + 1) = 'i' then Ada.Strings.Unbounded.Append (Result, Util.Strings.Image (Index)); Pos := Pos + 2; elsif Pos + 3 < Pattern'Last and then Pattern (Pos + 1) = 'd' and then Pattern (Pos + 2) = '{' then Pos := Pos + 3; First := Pos; while Pos <= Pattern'Last and Pattern (Pos) /= '}' loop Pos := Pos + 1; end loop; Append (Result, Util.Dates.Simple_Format (Pattern (First .. Pos - 1), Date)); Pos := Pos + 1; else Ada.Strings.Unbounded.Append (Result, Pattern (Pos)); Pos := Pos + 1; end if; end loop; return To_String (Result); end Format; -- ------------------------------ -- Initialize the file manager to roll the file referred by `Path` by using -- the pattern defined in `Pattern`. -- ------------------------------ procedure Initialize (Manager : in out File_Manager; Path : in String; Pattern : in String; Policy : in Policy_Type; Strategy : in Strategy_Type) is begin Manager.Deadline := Ada.Calendar.Clock; Manager.File_Path := To_Unbounded_String (Path); Manager.Pattern := To_Unbounded_String (Pattern); Manager.Cur_Index := 0; Manager.Policy := Policy.Kind; case Policy.Kind is when Size_Policy | Size_Time_Policy | Time_Policy => Manager.Max_Size := Policy.Size; Manager.Interval := Policy.Interval; when others => null; end case; Manager.Strategy := Strategy.Kind; case Strategy.Kind is when Ascending_Strategy | Descending_Strategy => Manager.Min_Index := Strategy.Min_Index; Manager.Max_Index := Strategy.Max_Index; Manager.Max_Files := Manager.Max_Index - Manager.Min_Index; when Direct_Strategy => Manager.Max_Files := Strategy.Max_Files; end case; Manager.Rollover; end Initialize; -- ------------------------------ -- Get the current path (it may or may not exist). -- ------------------------------ function Get_Current_Path (Manager : in File_Manager) return String is begin return To_String (Manager.File_Path); end Get_Current_Path; -- ------------------------------ -- Check if a rollover is necessary based on the rolling strategy. -- ------------------------------ function Is_Rollover_Necessary (Manager : in out File_Manager) return Boolean is Now : Ada.Calendar.Time; begin if Manager.Policy = No_Policy then return False; end if; if Manager.Policy = Time_Policy then Now := Ada.Calendar.Clock; if Now < Manager.Deadline then return False; end if; -- Continue checking if the path has changed. end if; declare Current : constant String := To_String (Manager.File_Path); Exists : constant Boolean := Ada.Directories.Exists (Current); begin if not Exists and Manager.Policy = Size_Policy then return False; end if; if Exists and then Manager.Policy in Size_Policy | Size_Time_Policy and then Ada.Directories.Size (Current) >= Manager.Max_Size then return True; end if; if Manager.Policy = Size_Policy then return False; end if; -- Time_Policy or Size_Time_Policy Now := Ada.Calendar.Clock; if Now < Manager.Deadline then return False; end if; -- Check if the file pattern was changed due to the date. declare Pat : constant String := To_String (Manager.Pattern); Path : constant String := Format (Pattern => Pat, Date => Now, Index => Manager.Cur_Index); begin -- Get a new deadline to check for time change. Manager.Deadline := Now + Duration (Manager.Interval); return Current /= Path; end; exception when Ada.Directories.Name_Error => -- Even if we check for file existence, an exception could -- be raised if the file is moved/deleted. return False; end; end Is_Rollover_Necessary; -- ------------------------------ -- Perform a rollover according to the strategy that was configured. -- ------------------------------ procedure Rollover (Manager : in out File_Manager) is begin case (Manager.Strategy) is when Ascending_Strategy => Manager.Rollover_Ascending; when Descending_Strategy => Manager.Rollover_Descending; when Direct_Strategy => Manager.Rollover_Direct; end case; end Rollover; procedure Rollover_Ascending (Manager : in out File_Manager) is Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Old : constant String := Manager.Get_Current_Path; Path : constant String := Format (Pattern => To_String (Manager.Pattern), Date => Now, Index => Manager.Cur_Index); Dir : constant String := Ada.Directories.Containing_Directory (Path); Names : Util.Strings.Vectors.Vector; First : Natural := 0; Last : Natural := 0; begin if Ada.Directories.Exists (Dir) then Manager.Eligible_Files (Dir, Names, First, Last); while Natural (Names.Length) > Manager.Max_Files loop begin Ada.Directories.Delete_File (Compose (Dir, Names.First_Element)); exception when Ada.Directories.Name_Error => null; end; Names.Delete_First; end loop; end if; Manager.Cur_Index := Last + 1; -- Too many files, rename old ones. if Manager.Cur_Index > Manager.Max_Index then Manager.Cur_Index := Manager.Max_Index - Natural (Names.Length); for Name of Names loop Manager.Rename (Compose (Dir, Name)); Manager.Cur_Index := Manager.Cur_Index + 1; end loop; end if; Manager.Rename (Old); end Rollover_Ascending; procedure Rename (Manager : in File_Manager; Old : in String) is Path : constant String := Format (Pattern => To_String (Manager.Pattern), Date => Manager.Deadline, Index => Manager.Cur_Index); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin if Ada.Directories.Exists (Old) then if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Path (Dir); end if; Util.Files.Rename (Old_Name => Old, New_Name => Path); end if; end Rename; procedure Rollover_Descending (Manager : in out File_Manager) is Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Old : constant String := Manager.Get_Current_Path; Path : constant String := Format (Pattern => To_String (Manager.Pattern), Date => Now, Index => Manager.Cur_Index); Dir : constant String := Ada.Directories.Containing_Directory (Path); Names : Util.Strings.Vectors.Vector; First : Natural := 0; Last : Natural := 0; begin if Ada.Directories.Exists (Dir) then Manager.Eligible_Files (Dir, Names, First, Last); while Natural (Names.Length) > Manager.Max_Files loop begin Ada.Directories.Delete_File (Compose (Dir, Names.Last_Element)); exception when Ada.Directories.Name_Error => null; end; Names.Delete_Last; end loop; end if; Manager.Cur_Index := First; if not Names.Is_Empty then Manager.Cur_Index := Manager.Min_Index + Natural (Names.Length); for Name of reverse Names loop Manager.Rename (Compose (Dir, Name)); Manager.Cur_Index := Manager.Cur_Index - 1; end loop; end if; Manager.Rename (Old); end Rollover_Descending; procedure Rollover_Direct (Manager : in out File_Manager) is begin null; end Rollover_Direct; -- ------------------------------ -- Get the regex pattern to identify a file that must be purged. -- The default is to extract the file pattern part of the file manager pattern. -- ------------------------------ function Get_Purge_Pattern (Manager : in File_Manager) return String is Full_Pat : constant String := To_String (Manager.Pattern); Name_Pat : constant String := Ada.Directories.Simple_Name (Full_Pat); Pos : Natural := Name_Pat'First; Result : Unbounded_String; Found : Boolean := False; begin while Pos <= Name_Pat'Last loop if Name_Pat (Pos) = '%' and then Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos + 1) = 'i' then if not Found then Append (Result, "([0-9]+)"); Found := True; else Append (Result, "[0-9]+"); end if; Pos := Pos + 2; elsif Pos + 3 < Name_Pat'Last and then Name_Pat (Pos + 1) = 'd' and then Name_Pat (Pos + 2) = '{' then Pos := Pos + 3; while Pos <= Name_Pat'Last and then Name_Pat (Pos) /= '}' loop if Pos + 3 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 3) = "YYYY" then Pos := Pos + 4; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "MM" then Pos := Pos + 2; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "dd" then Pos := Pos + 2; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "HH" then Pos := Pos + 2; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "mm" then Pos := Pos + 2; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "ss" then Pos := Pos + 2; Append (Result, "[0-9]+"); else Append (Result, Name_Pat (Pos)); Pos := Pos + 1; end if; end loop; Pos := Pos + 1; else Append (Result, Name_Pat (Pos)); Pos := Pos + 1; end if; end loop; return To_String (Result); end Get_Purge_Pattern; -- ------------------------------ -- Find the files that are eligible to purge in the given directory. -- ------------------------------ procedure Eligible_Files (Manager : in out File_Manager; Path : in String; Names : in out Util.Strings.Vectors.Vector; First_Index : out Natural; Last_Index : out Natural) is function Get_Index (Name : in String) return Natural; function Compare (Left, Right : in String) return Boolean; Search_Filter : constant Ada.Directories.Filter_Type := (Ada.Directories.Ordinary_File => True, Ada.Directories.Directory => False, Ada.Directories.Special_File => False); Pattern : constant String := Manager.Get_Purge_Pattern; Regex : constant GNAT.Regpat.Pattern_Matcher := GNAT.Regpat.Compile (Pattern); Glob1 : constant String := Util.Strings.Replace (Pattern, "([0-9]+)", "*", False); Glob2 : constant String := Util.Strings.Replace (Glob1, "[0-9]+", "*", False); Search : Ada.Directories.Search_Type; Ent : Ada.Directories.Directory_Entry_Type; function Get_Index (Name : in String) return Natural is Matches : GNAT.Regpat.Match_Array (0 .. 1); begin if GNAT.Regpat.Match (Regex, Name) then GNAT.Regpat.Match (Regex, Name, Matches); return Natural'Value (Name (Matches (1).First .. Matches (1).Last)); else return 0; end if; exception when others => return 0; end Get_Index; function Compare (Left, Right : in String) return Boolean is Left_Index : constant Natural := Get_Index (Left); Right_Index : constant Natural := Get_Index (Right); begin return Left_Index < Right_Index; end Compare; package Sort_Names is new Util.Strings.Vectors.Generic_Sorting (Compare); begin Ada.Directories.Start_Search (Search, Directory => Path, Pattern => Glob2, Filter => Search_Filter); while Ada.Directories.More_Entries (Search) loop Ada.Directories.Get_Next_Entry (Search, Ent); declare Name : constant String := Ada.Directories.Simple_Name (Ent); begin Names.Append (Name); end; end loop; Sort_Names.Sort (Names); if not Names.Is_Empty then First_Index := Get_Index (Names.First_Element); Last_Index := Get_Index (Names.Last_Element); else First_Index := Manager.Min_Index; Last_Index := Manager.Min_Index; end if; end Eligible_Files; end Util.Files.Rolling;
----------------------------------------------------------------------- -- util-files-rolling -- Rolling file manager -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; with Util.Dates.Simple_Format; package body Util.Files.Rolling is use type Ada.Calendar.Time; use type Ada.Directories.File_Size; -- ------------------------------ -- Format the file pattern with the date and index to produce a file path. -- ------------------------------ function Format (Pattern : in String; Date : in Ada.Calendar.Time; Index : in Natural) return String is Pos : Natural := Pattern'First; Result : Unbounded_String; Info : Util.Dates.Date_Record; First : Natural; begin Util.Dates.Split (Info, Date); while Pos <= Pattern'Last loop if Pattern (Pos) /= '%' or else Pos = Pattern'Last then Ada.Strings.Unbounded.Append (Result, Pattern (Pos)); Pos := Pos + 1; elsif Pattern (Pos + 1) = 'i' then Ada.Strings.Unbounded.Append (Result, Util.Strings.Image (Index)); Pos := Pos + 2; elsif Pos + 3 < Pattern'Last and then Pattern (Pos + 1) = 'd' and then Pattern (Pos + 2) = '{' then Pos := Pos + 3; First := Pos; while Pos <= Pattern'Last and Pattern (Pos) /= '}' loop Pos := Pos + 1; end loop; Append (Result, Util.Dates.Simple_Format (Pattern (First .. Pos - 1), Date)); Pos := Pos + 1; else Ada.Strings.Unbounded.Append (Result, Pattern (Pos)); Pos := Pos + 1; end if; end loop; return To_String (Result); end Format; -- ------------------------------ -- Initialize the file manager to roll the file referred by `Path` by using -- the pattern defined in `Pattern`. -- ------------------------------ procedure Initialize (Manager : in out File_Manager; Path : in String; Pattern : in String; Policy : in Policy_Type; Strategy : in Strategy_Type) is begin Manager.Deadline := Ada.Calendar.Clock; Manager.File_Path := To_Unbounded_String (Path); Manager.Pattern := To_Unbounded_String (Pattern); Manager.Cur_Index := 0; Manager.Policy := Policy.Kind; case Policy.Kind is when Size_Policy | Size_Time_Policy | Time_Policy => Manager.Max_Size := Policy.Size; Manager.Interval := Policy.Interval; when others => null; end case; Manager.Strategy := Strategy.Kind; case Strategy.Kind is when Ascending_Strategy | Descending_Strategy => Manager.Min_Index := Strategy.Min_Index; Manager.Max_Index := Strategy.Max_Index; Manager.Max_Files := Manager.Max_Index - Manager.Min_Index; when Direct_Strategy => Manager.Max_Files := Strategy.Max_Files; end case; Manager.Rollover; end Initialize; -- ------------------------------ -- Get the current path (it may or may not exist). -- ------------------------------ function Get_Current_Path (Manager : in File_Manager) return String is begin return To_String (Manager.File_Path); end Get_Current_Path; -- ------------------------------ -- Check if a rollover is necessary based on the rolling strategy. -- ------------------------------ function Is_Rollover_Necessary (Manager : in out File_Manager) return Boolean is Now : Ada.Calendar.Time; begin if Manager.Policy = No_Policy then return False; end if; if Manager.Policy = Time_Policy then Now := Ada.Calendar.Clock; if Now < Manager.Deadline then return False; end if; -- Continue checking if the path has changed. end if; declare Current : constant String := To_String (Manager.File_Path); Exists : constant Boolean := Ada.Directories.Exists (Current); begin if not Exists and Manager.Policy = Size_Policy then return False; end if; if Exists and then Manager.Policy in Size_Policy | Size_Time_Policy and then Ada.Directories.Size (Current) >= Manager.Max_Size then return True; end if; if Manager.Policy = Size_Policy then return False; end if; -- Time_Policy or Size_Time_Policy Now := Ada.Calendar.Clock; if Now < Manager.Deadline then return False; end if; -- Check if the file pattern was changed due to the date. declare Pat : constant String := To_String (Manager.Pattern); Path : constant String := Format (Pattern => Pat, Date => Now, Index => Manager.Cur_Index); begin -- Get a new deadline to check for time change. Manager.Deadline := Now + Duration (Manager.Interval); return Path /= Manager.Last_Path; end; exception when Ada.Directories.Name_Error => -- Even if we check for file existence, an exception could -- be raised if the file is moved/deleted. return False; end; end Is_Rollover_Necessary; -- ------------------------------ -- Perform a rollover according to the strategy that was configured. -- ------------------------------ procedure Rollover (Manager : in out File_Manager) is begin case (Manager.Strategy) is when Ascending_Strategy => Manager.Rollover_Ascending; when Descending_Strategy => Manager.Rollover_Descending; when Direct_Strategy => Manager.Rollover_Direct; end case; end Rollover; procedure Rollover_Ascending (Manager : in out File_Manager) is Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Old : constant String := Manager.Get_Current_Path; Path : constant String := Format (Pattern => To_String (Manager.Pattern), Date => Now, Index => Manager.Cur_Index); Dir : constant String := Ada.Directories.Containing_Directory (Path); Names : Util.Strings.Vectors.Vector; First : Natural := 0; Last : Natural := 0; begin if Ada.Directories.Exists (Dir) then Manager.Eligible_Files (Dir, Names, First, Last); while Natural (Names.Length) > Manager.Max_Files loop begin Ada.Directories.Delete_File (Compose (Dir, Names.First_Element)); exception when Ada.Directories.Name_Error => null; end; Names.Delete_First; end loop; end if; Manager.Cur_Index := Last + 1; -- Too many files, rename old ones. if Manager.Cur_Index > Manager.Max_Index then Manager.Cur_Index := Manager.Max_Index - Natural (Names.Length); for Name of Names loop Manager.Rename (Compose (Dir, Name)); Manager.Cur_Index := Manager.Cur_Index + 1; end loop; end if; Manager.Rename (Old); end Rollover_Ascending; procedure Rename (Manager : in out File_Manager; Old : in String) is Path : constant String := Format (Pattern => To_String (Manager.Pattern), Date => Manager.Deadline, Index => Manager.Cur_Index); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin if Ada.Directories.Exists (Old) then if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Path (Dir); end if; Util.Files.Rename (Old_Name => Old, New_Name => Path); Manager.Last_Path := To_Unbounded_String (Path); end if; end Rename; procedure Rollover_Descending (Manager : in out File_Manager) is Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Old : constant String := Manager.Get_Current_Path; Path : constant String := Format (Pattern => To_String (Manager.Pattern), Date => Now, Index => Manager.Cur_Index); Dir : constant String := Ada.Directories.Containing_Directory (Path); Names : Util.Strings.Vectors.Vector; First : Natural := 0; Last : Natural := 0; begin if Ada.Directories.Exists (Dir) then Manager.Eligible_Files (Dir, Names, First, Last); while Natural (Names.Length) > Manager.Max_Files loop begin Ada.Directories.Delete_File (Compose (Dir, Names.Last_Element)); exception when Ada.Directories.Name_Error => null; end; Names.Delete_Last; end loop; end if; Manager.Cur_Index := First; if not Names.Is_Empty then Manager.Cur_Index := Manager.Min_Index + Natural (Names.Length); for Name of reverse Names loop Manager.Rename (Compose (Dir, Name)); Manager.Cur_Index := Manager.Cur_Index - 1; end loop; end if; Manager.Rename (Old); end Rollover_Descending; procedure Rollover_Direct (Manager : in out File_Manager) is begin null; end Rollover_Direct; -- ------------------------------ -- Get the regex pattern to identify a file that must be purged. -- The default is to extract the file pattern part of the file manager pattern. -- ------------------------------ function Get_Purge_Pattern (Manager : in File_Manager) return String is Full_Pat : constant String := To_String (Manager.Pattern); Name_Pat : constant String := Ada.Directories.Simple_Name (Full_Pat); Pos : Natural := Name_Pat'First; Result : Unbounded_String; Found : Boolean := False; begin while Pos <= Name_Pat'Last loop if Name_Pat (Pos) = '%' and then Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos + 1) = 'i' then if not Found then Append (Result, "([0-9]+)"); Found := True; else Append (Result, "[0-9]+"); end if; Pos := Pos + 2; elsif Pos + 3 < Name_Pat'Last and then Name_Pat (Pos + 1) = 'd' and then Name_Pat (Pos + 2) = '{' then Pos := Pos + 3; while Pos <= Name_Pat'Last and then Name_Pat (Pos) /= '}' loop if Pos + 3 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 3) = "YYYY" then Pos := Pos + 4; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "MM" then Pos := Pos + 2; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "dd" then Pos := Pos + 2; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "HH" then Pos := Pos + 2; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "mm" then Pos := Pos + 2; Append (Result, "[0-9]+"); elsif Pos + 1 <= Name_Pat'Last and then Name_Pat (Pos .. Pos + 1) = "ss" then Pos := Pos + 2; Append (Result, "[0-9]+"); else Append (Result, Name_Pat (Pos)); Pos := Pos + 1; end if; end loop; Pos := Pos + 1; else Append (Result, Name_Pat (Pos)); Pos := Pos + 1; end if; end loop; return To_String (Result); end Get_Purge_Pattern; -- ------------------------------ -- Find the files that are eligible to purge in the given directory. -- ------------------------------ procedure Eligible_Files (Manager : in out File_Manager; Path : in String; Names : in out Util.Strings.Vectors.Vector; First_Index : out Natural; Last_Index : out Natural) is function Get_Index (Name : in String) return Natural; function Compare (Left, Right : in String) return Boolean; Search_Filter : constant Ada.Directories.Filter_Type := (Ada.Directories.Ordinary_File => True, Ada.Directories.Directory => False, Ada.Directories.Special_File => False); Pattern : constant String := Manager.Get_Purge_Pattern; Regex : constant GNAT.Regpat.Pattern_Matcher := GNAT.Regpat.Compile (Pattern); Glob1 : constant String := Util.Strings.Replace (Pattern, "([0-9]+)", "*", False); Glob2 : constant String := Util.Strings.Replace (Glob1, "[0-9]+", "*", False); Search : Ada.Directories.Search_Type; Ent : Ada.Directories.Directory_Entry_Type; function Get_Index (Name : in String) return Natural is Matches : GNAT.Regpat.Match_Array (0 .. 1); begin if GNAT.Regpat.Match (Regex, Name) then GNAT.Regpat.Match (Regex, Name, Matches); return Natural'Value (Name (Matches (1).First .. Matches (1).Last)); else return 0; end if; exception when others => return 0; end Get_Index; function Compare (Left, Right : in String) return Boolean is Left_Index : constant Natural := Get_Index (Left); Right_Index : constant Natural := Get_Index (Right); begin return Left_Index < Right_Index; end Compare; package Sort_Names is new Util.Strings.Vectors.Generic_Sorting (Compare); begin Ada.Directories.Start_Search (Search, Directory => Path, Pattern => Glob2, Filter => Search_Filter); while Ada.Directories.More_Entries (Search) loop Ada.Directories.Get_Next_Entry (Search, Ent); declare Name : constant String := Ada.Directories.Simple_Name (Ent); begin Names.Append (Name); end; end loop; Sort_Names.Sort (Names); if not Names.Is_Empty then First_Index := Get_Index (Names.First_Element); Last_Index := Get_Index (Names.Last_Element); else First_Index := Manager.Min_Index; Last_Index := Manager.Min_Index; end if; end Eligible_Files; end Util.Files.Rolling;
Add Last_Path and record it when Rename is called
Add Last_Path and record it when Rename is called
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e9457037c7b49361eb502f4593df7246f381ce6b
regtests/util-strings-tests.ads
regtests/util-strings-tests.ads
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Escape_Java (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); procedure Test_Starts_With (T : in out Test); procedure Test_Ends_With (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); end Util.Strings.Tests;
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018, 2020, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Strings.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Escape_Javascript (T : in out Test); procedure Test_Escape_Xml (T : in out Test); procedure Test_Escape_Java (T : in out Test); procedure Test_Unescape_Xml (T : in out Test); procedure Test_Capitalize (T : in out Test); procedure Test_To_Upper_Case (T : in out Test); procedure Test_To_Lower_Case (T : in out Test); procedure Test_To_Hex (T : in out Test); procedure Test_Measure_Copy (T : in out Test); procedure Test_Index (T : in out Test); procedure Test_Rindex (T : in out Test); procedure Test_Starts_With (T : in out Test); procedure Test_Ends_With (T : in out Test); -- Do some benchmark on String -> X hash mapped. procedure Test_Measure_Hash (T : in out Test); -- Test String_Ref creation procedure Test_String_Ref (T : in out Test); -- Benchmark comparison between the use of Iterate vs Query_Element. procedure Test_Perf_Vector (T : in out Test); -- Test perfect hash (samples/gperfhash) procedure Test_Perfect_Hash (T : in out Test); -- Test the token iteration. procedure Test_Iterate_Token (T : in out Test); -- Test formatting strings. procedure Test_Format (T : in out Test); end Util.Strings.Tests;
Add Test_Format procedure
Add Test_Format procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
1293bc69aac571793c5e87777a673b97803c276a
src/gen-artifacts-distribs-merges.adb
src/gen-artifacts-distribs-merges.adb
----------------------------------------------------------------------- -- gen-artifacts-distribs-merges -- Web file merge -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Strings.Fixed; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Files; with Util.Strings; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.Buffered; with EL.Expressions; with Gen.Utils; package body Gen.Artifacts.Distribs.Merges is use Util.Log; use Ada.Strings.Fixed; use Util.Beans.Objects; use Ada.Strings.Unbounded; procedure Process_Property (Rule : in out Merge_Rule; Node : in DOM.Core.Node); procedure Process_Replace (Rule : in out Merge_Rule; Node : in DOM.Core.Node); Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Merges"); -- ------------------------------ -- Extract the <property name='{name}'>{value}</property> to setup the -- EL context to evaluate the source and target links for the merge. -- ------------------------------ procedure Process_Property (Rule : in out Merge_Rule; Node : in DOM.Core.Node) is use Util.Beans.Objects.Maps; Name : constant String := Gen.Utils.Get_Attribute (Node, "name"); Value : constant String := Gen.Utils.Get_Data_Content (Node); Pos : constant Natural := Util.Strings.Index (Name, '.'); begin if Pos = 0 then Rule.Variables.Bind (Name, To_Object (Value)); return; end if; -- A composed name such as 'jquery.path' must be split so that we store -- the 'path' value within a 'jquery' Map_Bean object. We handle only -- one such composition. declare Param : constant String := Name (Name'First .. Pos - 1); Tag : constant Unbounded_String := To_Unbounded_String (Param); Var : constant EL.Expressions.Expression := Rule.Variables.Get_Variable (Tag); Val : Object := Rule.Params.Get_Value (Param); Child : Map_Bean_Access; begin if Is_Null (Val) then Child := new Map_Bean; Val := To_Object (Child); Rule.Params.Set_Value (Param, Val); else Child := To_Bean (Val); end if; Child.Set_Value (Name (Pos + 1 .. Name'Last), To_Object (Value)); if Var.Is_Null then Rule.Variables.Bind (Param, Val); end if; end; end Process_Property; procedure Process_Replace (Rule : in out Merge_Rule; Node : in DOM.Core.Node) is From : constant String := Gen.Utils.Get_Data_Content (Node, "from"); To : constant String := Gen.Utils.Get_Data_Content (Node, "to"); begin Rule.Replace.Include (From, To); end Process_Replace; procedure Iterate_Properties is new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Property); procedure Iterate_Replace is new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Replace); -- ------------------------------ -- Create a distribution rule to copy a set of files or directories. -- ------------------------------ function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is Result : constant Merge_Rule_Access := new Merge_Rule; begin Iterate_Properties (Result.all, Node, "property", False); Iterate_Replace (Result.all, Node, "replace", False); Result.Context.Set_Variable_Mapper (Result.Variables'Access); return Result.all'Access; end Create_Rule; -- ------------------------------ -- Get a name to qualify the installation rule (used for logs). -- ------------------------------ overriding function Get_Install_Name (Rule : in Merge_Rule) return String is pragma Unreferenced (Rule); begin return "merge"; end Get_Install_Name; overriding procedure Install (Rule : in Merge_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class) is use Ada.Streams; type Mode_Type is (MERGE_NONE, MERGE_LINK, MERGE_SCRIPT); procedure Error (Message : in String); function Get_Target_Path (Link : in String) return String; function Get_Filename (Line : in String) return String; function Get_Source (Line : in String; Tag : in String) return String; function Find_Match (Buffer : in Stream_Element_Array) return Stream_Element_Offset; procedure Prepare_Merge (Line : in String); procedure Include (Source : in String); procedure Process (Line : in String); Root_Dir : constant String := Util.Files.Compose (Context.Get_Result_Directory, To_String (Rule.Dir)); Source : constant String := Get_Source_Path (Files, False); Dir : constant String := Ada.Directories.Containing_Directory (Path); Build : constant String := Context.Get_Parameter ("dynamo.build"); Output : aliased Util.Streams.Files.File_Stream; Merge : aliased Util.Streams.Files.File_Stream; Text : Util.Streams.Texts.Print_Stream; Mode : Mode_Type := MERGE_NONE; Line_Num : Natural := 0; procedure Error (Message : in String) is Line : constant String := Util.Strings.Image (Line_Num); begin Context.Error (Source & ":" & Line & ": " & Message); end Error; function Get_Target_Path (Link : in String) return String is Expr : EL.Expressions.Expression; File : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Link, Rule.Context); File := Expr.Get_Value (Rule.Context); return Util.Files.Compose (Root_Dir, To_String (File)); end Get_Target_Path; function Get_Filename (Line : in String) return String is Pos : Natural := Index (Line, "link="); Last : Natural; begin if Pos > 0 then Mode := MERGE_LINK; else Pos := Index (Line, "script="); if Pos > 0 then Mode := MERGE_SCRIPT; end if; if Pos = 0 then return ""; end if; end if; Pos := Index (Line, "="); Last := Util.Strings.Index (Line, ' ', Pos + 1); if Last = 0 then return ""; end if; return Line (Pos + 1 .. Last - 1); end Get_Filename; function Get_Source (Line : in String; Tag : in String) return String is Pos : Natural := Index (Line, Tag); Last : Natural; begin if Pos = 0 then return ""; end if; Pos := Pos + Tag'Length; if Pos > Line'Last or else (Line (Pos) /= '"' and Line (Pos) /= ''') then return ""; end if; Last := Util.Strings.Index (Line, Line (Pos), Pos + 1); if Last = 0 then return ""; end if; return Line (Pos + 1 .. Last - 1); end Get_Source; procedure Prepare_Merge (Line : in String) is Name : constant String := Get_Filename (Line); Path : constant String := Get_Target_Path (Name); begin if Name'Length = 0 then Error ("invalid file name"); return; end if; case Mode is when MERGE_LINK => Text.Write ("<link media='screen' type='text/css' rel='stylesheet'" & " href='"); Text.Write (Name); Text.Write ("?build="); Text.Write (Build); Text.Write ("'/>" & ASCII.LF); when MERGE_SCRIPT => Text.Write ("<script type='text/javascript' src='"); Text.Write (Name); Text.Write ("?build="); Text.Write (Build); Text.Write ("'></script>" & ASCII.LF); when MERGE_NONE => null; end case; if Rule.Level >= Util.Log.INFO_LEVEL then Log.Info (" create {0}", Path); end if; Merge.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); end Prepare_Merge; Current_Match : Util.Strings.Maps.Cursor; function Find_Match (Buffer : in Stream_Element_Array) return Stream_Element_Offset is Iter : Util.Strings.Maps.Cursor := Rule.Replace.First; First : Stream_Element_Offset := Buffer'Last + 1; begin while Util.Strings.Maps.Has_Element (Iter) loop declare Value : constant String := Util.Strings.Maps.Key (Iter); Match : Stream_Element_Array (1 .. Value'Length); for Match'Address use Value'Address; Pos : Stream_Element_Offset; begin Pos := Buffer'First; while Pos + Match'Length < Buffer'Last loop if Buffer (Pos .. Pos + Match'Length - 1) = Match then if First > Pos then First := Pos; Current_Match := Iter; end if; exit; end if; Pos := Pos + 1; end loop; end; Util.Strings.Maps.Next (Iter); end loop; return First; end Find_Match; procedure Free is new Ada.Unchecked_Deallocation (Object => Ada.Streams.Stream_Element_Array, Name => Util.Streams.Buffered.Buffer_Access); procedure Include (Source : in String) is Target : constant String := Get_Target_Path (Source); Input : Util.Streams.Files.File_Stream; Size : Stream_Element_Offset; Last : Stream_Element_Offset; Pos : Stream_Element_Offset; Next : Stream_Element_Offset; Buffer : Util.Streams.Buffered.Buffer_Access; begin if Rule.Level >= Util.Log.INFO_LEVEL then Log.Info (" include {0}", Target); end if; Input.Open (Name => Target, Mode => Ada.Streams.Stream_IO.In_File); Size := Stream_Element_Offset (Ada.Directories.Size (Target)); Buffer := new Stream_Element_Array (1 .. Size); Input.Read (Buffer.all, Last); Input.Close; Pos := 1; while Pos < Last loop Next := Find_Match (Buffer (Pos .. Last)); if Next > Pos then Merge.Write (Buffer (Pos .. Next - 1)); end if; exit when Next >= Last; declare Value : constant String := Util.Strings.Maps.Key (Current_Match); Replace : constant String := Util.Strings.Maps.Element (Current_Match); Content : Stream_Element_Array (1 .. Replace'Length); for Content'Address use Replace'Address; begin Merge.Write (Content); Pos := Next + Value'Length; end; end loop; Free (Buffer); exception when Ex : Ada.IO_Exceptions.Name_Error => Error ("Cannot read: " & Ada.Exceptions.Exception_Message (Ex)); end Include; procedure Process (Line : in String) is Pos : Natural; begin Line_Num := Line_Num + 1; case Mode is when MERGE_NONE => Pos := Index (Line, "<!-- DYNAMO-MERGE-START "); if Pos = 0 then Text.Write (Line); Text.Write (ASCII.LF); return; end if; Text.Write (Line (Line'First .. Pos - 1)); Prepare_Merge (Line (Pos + 10 .. Line'Last)); when MERGE_LINK => Pos := Index (Line, "<!-- DYNAMO-MERGE-END "); if Pos > 0 then Merge.Close; Mode := MERGE_NONE; return; end if; Include (Get_Source (Line, "href=")); when MERGE_SCRIPT => Pos := Index (Line, "<!-- DYNAMO-MERGE-END "); if Pos > 0 then Merge.Close; Mode := MERGE_NONE; return; end if; Text.Write (Line (Line'First .. Pos - 1)); Include (Get_Source (Line, "src=")); end case; end Process; begin if Rule.Level >= Util.Log.INFO_LEVEL then Log.Info ("webmerge {0}", Path); end if; Ada.Directories.Create_Path (Dir); Output.Create (Name => Path, Mode => Ada.Streams.Stream_IO.Out_File); Text.Initialize (Output'Unchecked_Access, 16 * 1024); Util.Files.Read_File (Source, Process'Access); Text.Flush; Output.Close; end Install; end Gen.Artifacts.Distribs.Merges;
----------------------------------------------------------------------- -- gen-artifacts-distribs-merges -- Web file merge -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Strings.Fixed; with Ada.Streams.Stream_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Files; with Util.Strings; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.Buffered; with EL.Expressions; with Gen.Utils; package body Gen.Artifacts.Distribs.Merges is use Util.Log; use Ada.Strings.Fixed; use Util.Beans.Objects; use Ada.Strings.Unbounded; procedure Process_Property (Rule : in out Merge_Rule; Node : in DOM.Core.Node); procedure Process_Replace (Rule : in out Merge_Rule; Node : in DOM.Core.Node); Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Distribs.Merges"); -- ------------------------------ -- Extract the <property name='{name}'>{value}</property> to setup the -- EL context to evaluate the source and target links for the merge. -- ------------------------------ procedure Process_Property (Rule : in out Merge_Rule; Node : in DOM.Core.Node) is use Util.Beans.Objects.Maps; Name : constant String := Gen.Utils.Get_Attribute (Node, "name"); Value : constant String := Gen.Utils.Get_Data_Content (Node); Pos : constant Natural := Util.Strings.Index (Name, '.'); begin if Pos = 0 then Rule.Variables.Bind (Name, To_Object (Value)); return; end if; -- A composed name such as 'jquery.path' must be split so that we store -- the 'path' value within a 'jquery' Map_Bean object. We handle only -- one such composition. declare Param : constant String := Name (Name'First .. Pos - 1); Tag : constant Unbounded_String := To_Unbounded_String (Param); Var : constant EL.Expressions.Expression := Rule.Variables.Get_Variable (Tag); Val : Object := Rule.Params.Get_Value (Param); Child : Map_Bean_Access; begin if Is_Null (Val) then Child := new Map_Bean; Val := To_Object (Child); Rule.Params.Set_Value (Param, Val); else Child := Map_Bean_Access (To_Bean (Val)); end if; Child.Set_Value (Name (Pos + 1 .. Name'Last), To_Object (Value)); if Var.Is_Null then Rule.Variables.Bind (Param, Val); end if; end; end Process_Property; procedure Process_Replace (Rule : in out Merge_Rule; Node : in DOM.Core.Node) is From : constant String := Gen.Utils.Get_Data_Content (Node, "from"); To : constant String := Gen.Utils.Get_Data_Content (Node, "to"); begin Rule.Replace.Include (From, To); end Process_Replace; procedure Iterate_Properties is new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Property); procedure Iterate_Replace is new Gen.Utils.Iterate_Nodes (Merge_Rule, Process_Replace); -- ------------------------------ -- Create a distribution rule to copy a set of files or directories. -- ------------------------------ function Create_Rule (Node : in DOM.Core.Node) return Distrib_Rule_Access is Result : constant Merge_Rule_Access := new Merge_Rule; begin Iterate_Properties (Result.all, Node, "property", False); Iterate_Replace (Result.all, Node, "replace", False); Result.Context.Set_Variable_Mapper (Result.Variables'Access); return Result.all'Access; end Create_Rule; -- ------------------------------ -- Get a name to qualify the installation rule (used for logs). -- ------------------------------ overriding function Get_Install_Name (Rule : in Merge_Rule) return String is pragma Unreferenced (Rule); begin return "merge"; end Get_Install_Name; overriding procedure Install (Rule : in Merge_Rule; Path : in String; Files : in File_Vector; Context : in out Generator'Class) is use Ada.Streams; type Mode_Type is (MERGE_NONE, MERGE_LINK, MERGE_SCRIPT); procedure Error (Message : in String); function Get_Target_Path (Link : in String) return String; function Get_Filename (Line : in String) return String; function Get_Source (Line : in String; Tag : in String) return String; function Find_Match (Buffer : in Stream_Element_Array) return Stream_Element_Offset; procedure Prepare_Merge (Line : in String); procedure Include (Source : in String); procedure Process (Line : in String); Root_Dir : constant String := Util.Files.Compose (Context.Get_Result_Directory, To_String (Rule.Dir)); Source : constant String := Get_Source_Path (Files, False); Dir : constant String := Ada.Directories.Containing_Directory (Path); Build : constant String := Context.Get_Parameter ("dynamo.build"); Output : aliased Util.Streams.Files.File_Stream; Merge : aliased Util.Streams.Files.File_Stream; Text : Util.Streams.Texts.Print_Stream; Mode : Mode_Type := MERGE_NONE; Line_Num : Natural := 0; procedure Error (Message : in String) is Line : constant String := Util.Strings.Image (Line_Num); begin Context.Error (Source & ":" & Line & ": " & Message); end Error; function Get_Target_Path (Link : in String) return String is Expr : EL.Expressions.Expression; File : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Link, Rule.Context); File := Expr.Get_Value (Rule.Context); return Util.Files.Compose (Root_Dir, To_String (File)); end Get_Target_Path; function Get_Filename (Line : in String) return String is Pos : Natural := Index (Line, "link="); Last : Natural; begin if Pos > 0 then Mode := MERGE_LINK; else Pos := Index (Line, "script="); if Pos > 0 then Mode := MERGE_SCRIPT; end if; if Pos = 0 then return ""; end if; end if; Pos := Index (Line, "="); Last := Util.Strings.Index (Line, ' ', Pos + 1); if Last = 0 then return ""; end if; return Line (Pos + 1 .. Last - 1); end Get_Filename; function Get_Source (Line : in String; Tag : in String) return String is Pos : Natural := Index (Line, Tag); Last : Natural; begin if Pos = 0 then return ""; end if; Pos := Pos + Tag'Length; if Pos > Line'Last or else (Line (Pos) /= '"' and Line (Pos) /= ''') then return ""; end if; Last := Util.Strings.Index (Line, Line (Pos), Pos + 1); if Last = 0 then return ""; end if; return Line (Pos + 1 .. Last - 1); end Get_Source; procedure Prepare_Merge (Line : in String) is Name : constant String := Get_Filename (Line); Path : constant String := Get_Target_Path (Name); begin if Name'Length = 0 then Error ("invalid file name"); return; end if; case Mode is when MERGE_LINK => Text.Write ("<link media='screen' type='text/css' rel='stylesheet'" & " href='"); Text.Write (Name); Text.Write ("?build="); Text.Write (Build); Text.Write ("'/>" & ASCII.LF); when MERGE_SCRIPT => Text.Write ("<script type='text/javascript' src='"); Text.Write (Name); Text.Write ("?build="); Text.Write (Build); Text.Write ("'></script>" & ASCII.LF); when MERGE_NONE => null; end case; if Rule.Level >= Util.Log.INFO_LEVEL then Log.Info (" create {0}", Path); end if; Merge.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path); end Prepare_Merge; Current_Match : Util.Strings.Maps.Cursor; function Find_Match (Buffer : in Stream_Element_Array) return Stream_Element_Offset is Iter : Util.Strings.Maps.Cursor := Rule.Replace.First; First : Stream_Element_Offset := Buffer'Last + 1; begin while Util.Strings.Maps.Has_Element (Iter) loop declare Value : constant String := Util.Strings.Maps.Key (Iter); Match : Stream_Element_Array (1 .. Value'Length); for Match'Address use Value'Address; Pos : Stream_Element_Offset; begin Pos := Buffer'First; while Pos + Match'Length < Buffer'Last loop if Buffer (Pos .. Pos + Match'Length - 1) = Match then if First > Pos then First := Pos; Current_Match := Iter; end if; exit; end if; Pos := Pos + 1; end loop; end; Util.Strings.Maps.Next (Iter); end loop; return First; end Find_Match; procedure Free is new Ada.Unchecked_Deallocation (Object => Ada.Streams.Stream_Element_Array, Name => Util.Streams.Buffered.Buffer_Access); procedure Include (Source : in String) is Target : constant String := Get_Target_Path (Source); Input : Util.Streams.Files.File_Stream; Size : Stream_Element_Offset; Last : Stream_Element_Offset; Pos : Stream_Element_Offset; Next : Stream_Element_Offset; Buffer : Util.Streams.Buffered.Buffer_Access; begin if Rule.Level >= Util.Log.INFO_LEVEL then Log.Info (" include {0}", Target); end if; Input.Open (Name => Target, Mode => Ada.Streams.Stream_IO.In_File); Size := Stream_Element_Offset (Ada.Directories.Size (Target)); Buffer := new Stream_Element_Array (1 .. Size); Input.Read (Buffer.all, Last); Input.Close; Pos := 1; while Pos < Last loop Next := Find_Match (Buffer (Pos .. Last)); if Next > Pos then Merge.Write (Buffer (Pos .. Next - 1)); end if; exit when Next >= Last; declare Value : constant String := Util.Strings.Maps.Key (Current_Match); Replace : constant String := Util.Strings.Maps.Element (Current_Match); Content : Stream_Element_Array (1 .. Replace'Length); for Content'Address use Replace'Address; begin Merge.Write (Content); Pos := Next + Value'Length; end; end loop; Free (Buffer); exception when Ex : Ada.IO_Exceptions.Name_Error => Error ("Cannot read: " & Ada.Exceptions.Exception_Message (Ex)); end Include; procedure Process (Line : in String) is Pos : Natural; begin Line_Num := Line_Num + 1; case Mode is when MERGE_NONE => Pos := Index (Line, "<!-- DYNAMO-MERGE-START "); if Pos = 0 then Text.Write (Line); Text.Write (ASCII.LF); return; end if; Text.Write (Line (Line'First .. Pos - 1)); Prepare_Merge (Line (Pos + 10 .. Line'Last)); when MERGE_LINK => Pos := Index (Line, "<!-- DYNAMO-MERGE-END "); if Pos > 0 then Merge.Close; Mode := MERGE_NONE; return; end if; Include (Get_Source (Line, "href=")); when MERGE_SCRIPT => Pos := Index (Line, "<!-- DYNAMO-MERGE-END "); if Pos > 0 then Merge.Close; Mode := MERGE_NONE; return; end if; Text.Write (Line (Line'First .. Pos - 1)); Include (Get_Source (Line, "src=")); end case; end Process; begin if Rule.Level >= Util.Log.INFO_LEVEL then Log.Info ("webmerge {0}", Path); end if; Ada.Directories.Create_Path (Dir); Output.Create (Name => Path, Mode => Ada.Streams.Stream_IO.Out_File); Text.Initialize (Output'Unchecked_Access, 16 * 1024); Util.Files.Read_File (Source, Process'Access); Text.Flush; Output.Close; end Install; end Gen.Artifacts.Distribs.Merges;
Fix compilation with GNAT 2020
Fix compilation with GNAT 2020
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
604c892fbffd4aec2ee55505ef5b6ad1333ed33c
src/gen-artifacts-docs-googlecode.adb
src/gen-artifacts-docs-googlecode.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin if Line.Kind = L_LIST then Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_LIST_ITEM then Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; else if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line.Content); end if; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[https://github.com/stcarrez/dynamo Generated by Dynamo] from _" & Source & "_"); end Finish_Document; end Gen.Artifacts.Docs.Googlecode;
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Googlecode is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".wiki"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin if Line.Kind = L_LIST then Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_LIST_ITEM then Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_START_CODE then if Formatter.Need_NewLine then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, "{{{"); elsif Line.Kind = L_END_CODE then if Formatter.Need_NewLine then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, "}}}"); else if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line.Content); end if; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[https://github.com/stcarrez/dynamo Generated by Dynamo] from _" & Source & "_"); end Finish_Document; end Gen.Artifacts.Docs.Googlecode;
Format code according to L_START_CODE and L_END_CODE boundaries
Format code according to L_START_CODE and L_END_CODE boundaries
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
9a1debeb22e48919992807c6aec8c35d8c4db25b
src/asf-components-widgets-gravatars.adb
src/asf-components-widgets-gravatars.adb
----------------------------------------------------------------------- -- components-widgets-gravatars -- Gravatar Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; with GNAT.MD5; with ASF.Utils; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Gravatars is IMAGE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) -- ------------------------------ function Get_Link (Email : in String; Secure : in Boolean := False) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin if Secure then return "https://secure.gravatar.com/avatar/" & C; else return "http://www.gravatar.com/avatar/" & C; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIGravatar; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("img"); UI.Render_Attributes (Context, IMAGE_ATTRIBUTE_NAMES, Writer); declare Email : constant String := UI.Get_Attribute ("email", Context, ""); Size : Natural := UI.Get_Attribute ("size", Context, 80); Default : constant String := UI.Get_Attribute ("default", Context, "identicon"); Secure : constant Boolean := UI.Get_Attribute ("secure", Context, False); D : constant String := Util.Strings.Image (Size); Alt : constant String := UI.Get_Attribute ("alt", Context, ""); begin if Size < 0 or Size > 2048 then Size := 80; end if; Writer.Write_Attribute ("width", D); Writer.Write_Attribute ("height", D); if Alt'Length > 0 then Writer.Write_Attribute ("alt", Alt); else Writer.Write_Attribute ("alt", Email); end if; Writer.Write_Attribute ("src", Get_Link (Email, Secure) & "?d=" & Default & "&s=" & D); end; Writer.End_Element ("img"); end if; end Encode_Begin; begin Utils.Set_Text_Attributes (IMAGE_ATTRIBUTE_NAMES); end ASF.Components.Widgets.Gravatars;
----------------------------------------------------------------------- -- components-widgets-gravatars -- Gravatar Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings.Transforms; with GNAT.MD5; with ASF.Utils; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Gravatars is IMAGE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Given an Email address, return the Gravatar link to the user image. -- (See http://en.gravatar.com/site/implement/hash/ and -- http://en.gravatar.com/site/implement/images/) -- ------------------------------ function Get_Link (Email : in String; Secure : in Boolean := False) return String is E : constant String := Util.Strings.Transforms.To_Lower_Case (Email); C : constant GNAT.MD5.Message_Digest := GNAT.MD5.Digest (E); begin if Secure then return "https://secure.gravatar.com/avatar/" & C; else return "http://www.gravatar.com/avatar/" & C; end if; end Get_Link; -- ------------------------------ -- Render an image with the source link created from an email address to the Gravatars service. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIGravatar; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("img"); UI.Render_Attributes (Context, IMAGE_ATTRIBUTE_NAMES, Writer); declare Email : constant String := UI.Get_Attribute ("email", Context, ""); Size : Integer := UI.Get_Attribute ("size", Context, 80); Default : constant String := UI.Get_Attribute ("default", Context, "identicon"); Secure : constant Boolean := UI.Get_Attribute ("secure", Context, False); D : constant String := Util.Strings.Image (Size); Alt : constant String := UI.Get_Attribute ("alt", Context, ""); begin if Size <= 0 or Size > 2048 then Size := 80; end if; Writer.Write_Attribute ("width", D); Writer.Write_Attribute ("height", D); if Alt'Length > 0 then Writer.Write_Attribute ("alt", Alt); else Writer.Write_Attribute ("alt", Email); end if; Writer.Write_Attribute ("src", Get_Link (Email, Secure) & "?d=" & Default & "&s=" & D); end; Writer.End_Element ("img"); end if; end Encode_Begin; begin Utils.Set_Text_Attributes (IMAGE_ATTRIBUTE_NAMES); end ASF.Components.Widgets.Gravatars;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
da9568af3ab4a73b93568b07c41e695f8929609e
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "47"; copyright_years : constant String := "2015-2020"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; spkg_nls : constant String := "nls"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-8.0"; default_lua : constant String := "5.3"; default_perl : constant String := "5.30"; default_pgsql : constant String := "12"; default_php : constant String := "7.4"; default_python3 : constant String := "3.8"; default_ruby : constant String := "2.7"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_binutils : constant String := "binutils:ravensys"; default_compiler : constant String := "gcc9"; previous_default : constant String := "gcc8"; compiler_version : constant String := "9.3.0"; previous_compiler : constant String := "9.2.0"; binutils_version : constant String := "2.34"; previous_binutils : constant String := "2.33.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; task_stack_limit : constant := 10_000_000; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "47"; copyright_years : constant String := "2015-2020"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; spkg_nls : constant String := "nls"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-8.0"; default_lua : constant String := "5.3"; default_perl : constant String := "5.30"; default_pgsql : constant String := "12"; default_php : constant String := "7.4"; default_python3 : constant String := "3.8"; default_ruby : constant String := "2.7"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_binutils : constant String := "binutils:ravensys"; default_compiler : constant String := "gcc9"; previous_default : constant String := "gcc9"; compiler_version : constant String := "9.3.0"; previous_compiler : constant String := "9.2.0"; binutils_version : constant String := "2.34"; previous_binutils : constant String := "2.33.1"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; task_stack_limit : constant := 10_000_000; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 64; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/ravensw"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Fix previous compiler
Fix previous compiler
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
6ea55ee94158955b91601677f84e6d4ff85dc69b
awa/src/awa-permissions-services.adb
awa/src/awa-permissions-services.adb
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions.Entities; with ADO.Statements; with Util.Log.Loggers; with Security.Policies.Roles; with Security.Policies.URLs; with AWA.Permissions.Models; with AWA.Services.Contexts; package body AWA.Permissions.Services is use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions.Services"); -- ------------------------------ -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. -- ------------------------------ function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : constant String := Util.Beans.Objects.To_String (Name); Result : Boolean; begin if Util.Beans.Objects.Is_Empty (Name) or Context = null then Result := False; elsif Util.Beans.Objects.Is_Empty (Entity) then Result := Context.Has_Permission (Perm); else declare P : Entity_Permission (Security.Permissions.Get_Permission_Index (Perm)); begin P.Entity := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Entity)); Result := Context.Has_Permission (P); end; end if; return Util.Beans.Objects.To_Object (Result); exception when Security.Permissions.Invalid_Name => Log.Error ("Invalid permission {0}", Perm); raise; end Has_Permission; URI : aliased constant String := "http://code.google.com/p/ada-awa/auth"; -- ------------------------------ -- Register the security EL functions in the EL mapper. -- ------------------------------ procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "hasPermission", Namespace => URI, Func => Has_Permission'Access, Optimize => False); end Set_Functions; -- ------------------------------ -- 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; Workspace : in ADO.Identifier; 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.Set_Workspace_Id (Workspace); 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; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ) 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.Set_Workspace_Id (Workspace); 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; Workspace : in ADO.Identifier; 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, Workspace, 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); RP : constant Security.Policies.Roles.Role_Policy_Access := new Security.Policies.Roles.Role_Policy; RU : constant Security.Policies.URLs.URL_Policy_Access := new Security.Policies.URLs.URL_Policy; RE : constant Entity_Policy_Access := new Entity_Policy; begin Result.Add_Policy (RP.all'Access); Result.Add_Policy (RU.all'Access); Result.Add_Policy (RE.all'Access); Result.Set_Application (App); Log.Info ("Creation of the AWA Permissions manager"); return Result.all'Access; end Create_Permission_Manager; -- ------------------------------ -- Delete all the permissions for a user and on the given workspace. -- ------------------------------ procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Workspace : in ADO.Identifier) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (Models.ACL_TABLE); Result : Natural; begin Stmt.Set_Filter (Filter => "workspace_id = ? AND user_id = ?"); Stmt.Add_Param (Value => Workspace); Stmt.Add_Param (Value => User); Stmt.Execute (Result); Log.Info ("Deleted {0} permissions for user {1} in workspace {2}", Natural'Image (Result), ADO.Identifier'Image (User), ADO.Identifier'Image (Workspace)); end Delete_Permissions; end AWA.Permissions.Services;
----------------------------------------------------------------------- -- awa-permissions-services -- Permissions controller -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions.Entities; with ADO.Statements; with Util.Log.Loggers; with Security.Policies.URLs; with AWA.Permissions.Models; with AWA.Services.Contexts; package body AWA.Permissions.Services is use ADO.Sessions; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions.Services"); -- ------------------------------ -- Check if the permission with the name <tt>Name</tt> is granted for the current user. -- If the <tt>Entity</tt> is defined, an <tt>Entity_Permission</tt> is created and verified. -- Returns True if the user is granted the given permission. -- ------------------------------ function Has_Permission (Name : in Util.Beans.Objects.Object; Entity : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : constant String := Util.Beans.Objects.To_String (Name); Result : Boolean; begin if Util.Beans.Objects.Is_Empty (Name) or Context = null then Result := False; elsif Util.Beans.Objects.Is_Empty (Entity) then Result := Context.Has_Permission (Perm); else declare P : Entity_Permission (Security.Permissions.Get_Permission_Index (Perm)); begin P.Entity := ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Entity)); Result := Context.Has_Permission (P); end; end if; return Util.Beans.Objects.To_Object (Result); exception when Security.Permissions.Invalid_Name => Log.Error ("Invalid permission {0}", Perm); raise; end Has_Permission; URI : aliased constant String := "http://code.google.com/p/ada-awa/auth"; -- ------------------------------ -- Register the security EL functions in the EL mapper. -- ------------------------------ procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "hasPermission", Namespace => URI, Func => Has_Permission'Access, Optimize => False); end Set_Functions; -- ------------------------------ -- 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; Workspace : in ADO.Identifier; 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.Set_Workspace_Id (Workspace); 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; -- ------------------------------ -- Get the role names that grant the given permission. -- ------------------------------ function Get_Role_Names (Manager : in Permission_Manager; Permission : in Security.Permissions.Permission_Index) return Security.Policies.Roles.Role_Name_Array is begin return Manager.Roles.Get_Role_Names (Manager.Roles.Get_Grants (Permission)); end Get_Role_Names; -- ------------------------------ -- Add a permission for the user <b>User</b> to access the entity identified by -- <b>Entity</b> which is of type <b>Kind</b>. -- ------------------------------ procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Identifier; Kind : in ADO.Entity_Type; Workspace : in ADO.Identifier; Permission : in Permission_Type := READ) 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.Set_Workspace_Id (Workspace); 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; Workspace : in ADO.Identifier; 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, Workspace, 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); RP : constant Security.Policies.Roles.Role_Policy_Access := new Security.Policies.Roles.Role_Policy; RU : constant Security.Policies.URLs.URL_Policy_Access := new Security.Policies.URLs.URL_Policy; RE : constant Entity_Policy_Access := new Entity_Policy; begin Result.Add_Policy (RP.all'Access); Result.Add_Policy (RU.all'Access); Result.Add_Policy (RE.all'Access); Result.Set_Application (App); Log.Info ("Creation of the AWA Permissions manager"); return Result.all'Access; end Create_Permission_Manager; -- ------------------------------ -- Delete all the permissions for a user and on the given workspace. -- ------------------------------ procedure Delete_Permissions (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Workspace : in ADO.Identifier) is Stmt : ADO.Statements.Delete_Statement := Session.Create_Statement (Models.ACL_TABLE); Result : Natural; begin Stmt.Set_Filter (Filter => "workspace_id = ? AND user_id = ?"); Stmt.Add_Param (Value => Workspace); Stmt.Add_Param (Value => User); Stmt.Execute (Result); Log.Info ("Deleted {0} permissions for user {1} in workspace {2}", Natural'Image (Result), ADO.Identifier'Image (User), ADO.Identifier'Image (Workspace)); end Delete_Permissions; end AWA.Permissions.Services;
Implement the Get_Role_Names function
Implement the Get_Role_Names function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7e0a6f0575cc39219eacd23c2f58f084530e4466
awa/src/awa.ads
awa/src/awa.ads
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009 - 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = AWA Core == -- -- @include awa-applications.ads -- @include awa-modules.ads -- @include awa-permissions.ads -- @include awa-events.ads -- @include awa.xml package AWA is pragma Pure; end AWA;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009 - 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = AWA Core == -- -- @include awa-applications.ads -- @include awa-modules.ads -- @include awa-permissions.ads -- @include awa-events.ads -- @include awa-commands.ads -- @include awa.xml package AWA is pragma Pure; end AWA;
Include the AWA commands documentation
Include the AWA commands documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e461508f5c35a24116bb4ca61844c5c9d89d0f8a
src/gen-generator.adb
src/gen-generator.adb
----------------------------------------------------------------------- -- Gen -- Code 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 Ada.Directories; with Ada.IO_Exceptions; with Input_Sources.File; with DOM.Core.Documents; with DOM.Readers; with Sax.Readers; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Applications.Views; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Functions; with EL.Variables; with EL.Variables.Default; with Gen.Model; with Gen.Utils; with Util.Files; with Util.Log.Loggers; package body Gen.Generator is use ASF; use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Generator"); RESULT_DIR : constant String := "generator.output.dir"; function To_Ada_Type (Name : EL.Objects.Object) return EL.Objects.Object; function Indent (Value : EL.Objects.Object) return EL.Objects.Object; -- EL Function to translate a model type to the key enum value function To_Key_Enum (Name : EL.Objects.Object) return EL.Objects.Object; -- ------------------------------ -- EL Function to translate a model type to an Ada implementation type -- ------------------------------ function To_Ada_Type (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "String" then return EL.Objects.To_Object (String '("Unbounded_String")); elsif Value = "Integer" or Value = "int" then return EL.Objects.To_Object (String '("Integer")); else return Name; end if; end To_Ada_Type; -- ------------------------------ -- EL Function to check whether a type is an integer type -- ------------------------------ function Is_Integer_Type (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "Integer" or Value = "int" then return EL.Objects.To_Object (True); else return EL.Objects.To_Object (False); end if; end Is_Integer_Type; KEY_INTEGER_LABEL : constant String := "KEY_INTEGER"; KEY_STRING_LABEL : constant String := "KEY_STRING"; -- ------------------------------ -- EL Function to translate a model type to the key enum value -- ------------------------------ function To_Key_Enum (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "Integer" or Value = "int" or Value = "Identifier" or Value = "ADO.Identifier" then return EL.Objects.To_Object (KEY_INTEGER_LABEL); else return EL.Objects.To_Object (KEY_STRING_LABEL); end if; end To_Key_Enum; -- ------------------------------ -- EL function to indent the code -- ------------------------------ function Indent (Value : EL.Objects.Object) return EL.Objects.Object is S : constant String := EL.Objects.To_String (Value); Result : constant String (S'Range) := (others => ' '); begin return EL.Objects.To_Object (Result); end Indent; -- ------------------------------ -- EL function to indent the code -- ------------------------------ function To_Sql_Type (Value : EL.Objects.Object) return EL.Objects.Object is Name : constant String := EL.Objects.To_String (Value); Result : Unbounded_String; begin if Name = "Identifier" then Append (Result, "BIGINT NOT NULL"); elsif Name = "Integer" then Append (Result, "INTEGER"); elsif Name = "String" then Append (Result, "VARCHAR(255)"); elsif Name = "Date" then Append (Result, "DATE"); else Append (Result, "VARCHAR(255)"); end if; return EL.Objects.To_Object (Result); end To_Sql_Type; -- ------------------------------ -- Register the generator EL functions -- ------------------------------ procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is URI : constant String := "http://code.google.com/p/ada-ado/generator"; begin Mapper.Set_Function (Name => "adaType", Namespace => URI, Func => To_Ada_Type'Access); Mapper.Set_Function (Name => "indent", Namespace => URI, Func => Indent'Access); Mapper.Set_Function (Name => "isInteger", Namespace => URI, Func => Is_Integer_Type'Access); Mapper.Set_Function (Name => "sqlType", Namespace => URI, Func => To_Sql_Type'Access); Mapper.Set_Function (Name => "keyEnum", Namespace => URI, Func => To_Key_Enum'Access); end Set_Functions; -- ------------------------------ -- Initialize the generator -- ------------------------------ procedure Initialize (H : in out Handler) is procedure Register_Funcs is new ASF.Applications.Main.Register_Functions (Set_Functions); begin H.Conf.Set (ASF.Applications.VIEW_IGNORE_WHITE_SPACES, "false"); H.Conf.Set (ASF.Applications.VIEW_ESCAPE_UNKNOWN_TAGS, "false"); H.Conf.Set (ASF.Applications.VIEW_IGNORE_EMPTY_LINES, "true"); H.Conf.Set (ASF.Applications.VIEW_FILE_EXT, ""); if not H.Conf.Exists (ASF.Applications.VIEW_DIR) then H.Set_Template_Directory ("templates/"); end if; H.Initialize (H.Conf); Register_Funcs (H); end Initialize; -- ------------------------------ -- Set the directory where template files are stored. -- ------------------------------ procedure Set_Template_Directory (H : in out Handler; Path : in String) is begin H.Conf.Set (ASF.Applications.VIEW_DIR, Path); end Set_Template_Directory; -- ------------------------------ -- Set the directory where results files are generated. -- ------------------------------ procedure Set_Result_Directory (H : in out Handler; Path : in String) is begin H.Conf.Set (RESULT_DIR, Path); end Set_Result_Directory; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (H : in out Handler; Node : in DOM.Core.Node) is begin H.Model.Initialize (Node); end Register_Mapping; -- ------------------------------ -- 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 is begin return H.Status; end Get_Status; -- ------------------------------ -- Report an error and set the exit status accordingly -- ------------------------------ procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is begin Log.Error (Message, Arg1, Arg2); H.Status := 1; end Error; -- ------------------------------ -- Read the XML model file -- ------------------------------ procedure Read_Model (H : in out Handler; File : in String) is Read : Input_Sources.File.File_Input; My_Tree_Reader : DOM.Readers.Tree_Reader; Name_Start : Natural; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Handler, Process => Register_Mapping); begin Log.Info ("Reading model file {0}", File); -- Base file name should be used as the public Id Name_Start := File'Last; while Name_Start >= File'First and then File (Name_Start) /= '/' loop Name_Start := Name_Start - 1; end loop; Input_Sources.File.Open (File, Read); -- Full name is used as the system id Input_Sources.File.Set_System_Id (Read, File); Input_Sources.File.Set_Public_Id (Read, File (Name_Start + 1 .. File'Last)); DOM.Readers.Set_Feature (My_Tree_Reader, Sax.Readers.Validation_Feature, False); DOM.Readers.Parse (My_Tree_Reader, Read); Input_Sources.File.Close (Read); H.Doc := DOM.Readers.Get_Tree (My_Tree_Reader); H.Root := DOM.Core.Documents.Get_Element (H.Doc); Iterate (H, H.Root, "hibernate-mapping"); exception when Ada.IO_Exceptions.Name_Error => H.Error ("Model file {0} does not exist", File); end Read_Model; -- ------------------------------ -- Generate the code using the template file -- ------------------------------ procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access) is Context : aliased Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; Resolver : aliased EL.Contexts.Default.Default_ELResolver; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin Log.Info ("Generating {0}", File); -- Model.Initialize (H.Model); Resolver.Register (To_Unbounded_String ("model"), Model.all'Unchecked_Access); -- Context.Set_Response_Writer (Writer'Unchecked_Access); -- Context.Set_ELContext (ELContext'Unchecked_Access); -- ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); -- ELContext.Set_Resolver (Resolver'Unchecked_Access); -- Writer.Initialize ("text/plain", "UTF-8", 8192); -- H.Set_Context (Context'Unchecked_Access); -- H.Restore_View (File, Context, View); H.Dispatch (Page => File, Request => Req, Response => Reply); declare Dir : constant String := H.Conf.Get (RESULT_DIR, "./"); Result : constant EL.Objects.Object := View.Get_Root.Get_Attribute (Context, "file"); Path : constant String := Dir & EL.Objects.To_String (Result); Content : Unbounded_String; begin Log.Info ("Writing result file {0}", Path); Reply.Read_Content (Content); Util.Files.Write_File (Path => Path, Content => Content); end; end Generate; -- ------------------------------ -- Generate the code using the template file -- ------------------------------ procedure Generate (H : in out Handler; Mode : in Iteration_Mode; File : in String) is begin case Mode is when ITERATION_PACKAGE => declare Pos : Gen.Model.Tables.Package_Cursor := H.Model.First; begin while Gen.Model.Tables.Has_Element (Pos) loop H.Generate (File, Gen.Model.Tables.Element (Pos).all'Access); Gen.Model.Tables.Next (Pos); end loop; end; when ITERATION_TABLE => H.Generate (File, H.Model'Unchecked_Access); end case; end Generate; -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Iteration_Mode; Name : in String) is use Ada.Directories; Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; Dir : constant String := H.Conf.Get (ASF.Applications.VIEW_DIR); Path : constant String := Dir & Name; begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read model directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare File_Path : constant String := Full_Name (Ent); begin H.Generate (Mode, File_Path); end; end loop; exception when Ada.IO_Exceptions.Name_Error => H.Error ("Template directory {0} does not exist", Path); end Generate_All; end Gen.Generator;
----------------------------------------------------------------------- -- Gen -- Code 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 Ada.Directories; with Ada.IO_Exceptions; with Input_Sources.File; with DOM.Core.Documents; with DOM.Readers; with Sax.Readers; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Applications.Views; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Functions; with Gen.Model; with Gen.Utils; with Util.Files; with Util.Log.Loggers; package body Gen.Generator is use ASF; use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Generator"); RESULT_DIR : constant String := "generator.output.dir"; function To_Ada_Type (Name : EL.Objects.Object) return EL.Objects.Object; function Indent (Value : EL.Objects.Object) return EL.Objects.Object; -- EL Function to translate a model type to the key enum value function To_Key_Enum (Name : EL.Objects.Object) return EL.Objects.Object; -- ------------------------------ -- EL Function to translate a model type to an Ada implementation type -- ------------------------------ function To_Ada_Type (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "String" then return EL.Objects.To_Object (String '("Unbounded_String")); elsif Value = "Integer" or Value = "int" then return EL.Objects.To_Object (String '("Integer")); else return Name; end if; end To_Ada_Type; -- ------------------------------ -- EL Function to check whether a type is an integer type -- ------------------------------ function Is_Integer_Type (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "Integer" or Value = "int" then return EL.Objects.To_Object (True); else return EL.Objects.To_Object (False); end if; end Is_Integer_Type; KEY_INTEGER_LABEL : constant String := "KEY_INTEGER"; KEY_STRING_LABEL : constant String := "KEY_STRING"; -- ------------------------------ -- EL Function to translate a model type to the key enum value -- ------------------------------ function To_Key_Enum (Name : EL.Objects.Object) return EL.Objects.Object is Value : constant String := EL.Objects.To_String (Name); begin if Value = "Integer" or Value = "int" or Value = "Identifier" or Value = "ADO.Identifier" then return EL.Objects.To_Object (KEY_INTEGER_LABEL); else return EL.Objects.To_Object (KEY_STRING_LABEL); end if; end To_Key_Enum; -- ------------------------------ -- EL function to indent the code -- ------------------------------ function Indent (Value : EL.Objects.Object) return EL.Objects.Object is S : constant String := EL.Objects.To_String (Value); Result : constant String (S'Range) := (others => ' '); begin return EL.Objects.To_Object (Result); end Indent; -- ------------------------------ -- EL function to indent the code -- ------------------------------ function To_Sql_Type (Value : EL.Objects.Object) return EL.Objects.Object is Name : constant String := EL.Objects.To_String (Value); Result : Unbounded_String; begin if Name = "Identifier" then Append (Result, "BIGINT NOT NULL"); elsif Name = "Integer" then Append (Result, "INTEGER"); elsif Name = "String" then Append (Result, "VARCHAR(255)"); elsif Name = "Date" then Append (Result, "DATE"); else Append (Result, "VARCHAR(255)"); end if; return EL.Objects.To_Object (Result); end To_Sql_Type; -- ------------------------------ -- Register the generator EL functions -- ------------------------------ procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is URI : constant String := "http://code.google.com/p/ada-ado/generator"; begin Mapper.Set_Function (Name => "adaType", Namespace => URI, Func => To_Ada_Type'Access); Mapper.Set_Function (Name => "indent", Namespace => URI, Func => Indent'Access); Mapper.Set_Function (Name => "isInteger", Namespace => URI, Func => Is_Integer_Type'Access); Mapper.Set_Function (Name => "sqlType", Namespace => URI, Func => To_Sql_Type'Access); Mapper.Set_Function (Name => "keyEnum", Namespace => URI, Func => To_Key_Enum'Access); end Set_Functions; -- ------------------------------ -- Initialize the generator -- ------------------------------ procedure Initialize (H : in out Handler) is procedure Register_Funcs is new ASF.Applications.Main.Register_Functions (Set_Functions); begin H.Conf.Set (ASF.Applications.VIEW_IGNORE_WHITE_SPACES, "false"); H.Conf.Set (ASF.Applications.VIEW_ESCAPE_UNKNOWN_TAGS, "false"); H.Conf.Set (ASF.Applications.VIEW_IGNORE_EMPTY_LINES, "true"); H.Conf.Set (ASF.Applications.VIEW_FILE_EXT, ""); if not H.Conf.Exists (ASF.Applications.VIEW_DIR) then H.Set_Template_Directory ("templates/"); end if; H.Initialize (H.Conf); Register_Funcs (H); end Initialize; -- ------------------------------ -- Set the directory where template files are stored. -- ------------------------------ procedure Set_Template_Directory (H : in out Handler; Path : in String) is begin H.Conf.Set (ASF.Applications.VIEW_DIR, Path); end Set_Template_Directory; -- ------------------------------ -- Set the directory where results files are generated. -- ------------------------------ procedure Set_Result_Directory (H : in out Handler; Path : in String) is begin H.Conf.Set (RESULT_DIR, Path); end Set_Result_Directory; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (H : in out Handler; Node : in DOM.Core.Node) is begin H.Model.Initialize (Node); end Register_Mapping; -- ------------------------------ -- 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 is begin return H.Status; end Get_Status; -- ------------------------------ -- Report an error and set the exit status accordingly -- ------------------------------ procedure Error (H : in out Handler; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is begin Log.Error (Message, Arg1, Arg2); H.Status := 1; end Error; -- ------------------------------ -- Read the XML model file -- ------------------------------ procedure Read_Model (H : in out Handler; File : in String) is Read : Input_Sources.File.File_Input; My_Tree_Reader : DOM.Readers.Tree_Reader; Name_Start : Natural; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Handler, Process => Register_Mapping); begin Log.Info ("Reading model file {0}", File); -- Base file name should be used as the public Id Name_Start := File'Last; while Name_Start >= File'First and then File (Name_Start) /= '/' loop Name_Start := Name_Start - 1; end loop; Input_Sources.File.Open (File, Read); -- Full name is used as the system id Input_Sources.File.Set_System_Id (Read, File); Input_Sources.File.Set_Public_Id (Read, File (Name_Start + 1 .. File'Last)); DOM.Readers.Set_Feature (My_Tree_Reader, Sax.Readers.Validation_Feature, False); DOM.Readers.Parse (My_Tree_Reader, Read); Input_Sources.File.Close (Read); H.Doc := DOM.Readers.Get_Tree (My_Tree_Reader); H.Root := DOM.Core.Documents.Get_Element (H.Doc); Iterate (H, H.Root, "hibernate-mapping"); exception when Ada.IO_Exceptions.Name_Error => H.Error ("Model file {0} does not exist", File); end Read_Model; -- ------------------------------ -- Generate the code using the template file -- ------------------------------ procedure Generate (H : in out Handler; File : in String; Model : in Gen.Model.Definition_Access) is Context : aliased Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; Resolver : aliased EL.Contexts.Default.Default_ELResolver; Req : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Bean : constant EL.Objects.Object := EL.Objects.To_Object (Model.all'Unchecked_Access); begin Log.Info ("Generating {0}", File); Req.Set_Attribute (Name => "model", Value => Bean); Resolver.Register (To_Unbounded_String ("model"), Model.all'Unchecked_Access); H.Dispatch (Page => File, Request => Req, Response => Reply); declare Dir : constant String := H.Conf.Get (RESULT_DIR, "./"); Result : constant EL.Objects.Object := View.Get_Root.Get_Attribute (Context, "file"); Path : constant String := Dir & EL.Objects.To_String (Result); Content : Unbounded_String; begin Log.Info ("Writing result file {0}", Path); Reply.Read_Content (Content); Util.Files.Write_File (Path => Path, Content => Content); end; end Generate; -- ------------------------------ -- Generate the code using the template file -- ------------------------------ procedure Generate (H : in out Handler; Mode : in Iteration_Mode; File : in String) is begin case Mode is when ITERATION_PACKAGE => declare Pos : Gen.Model.Tables.Package_Cursor := H.Model.First; begin while Gen.Model.Tables.Has_Element (Pos) loop H.Generate (File, Gen.Model.Tables.Element (Pos).all'Access); Gen.Model.Tables.Next (Pos); end loop; end; when ITERATION_TABLE => H.Generate (File, H.Model'Unchecked_Access); end case; end Generate; -- Generate all the code generation files stored in the directory procedure Generate_All (H : in out Handler; Mode : in Iteration_Mode; Name : in String) is use Ada.Directories; Search : Search_Type; Filter : constant Filter_Type := (others => True); Ent : Directory_Entry_Type; Dir : constant String := H.Conf.Get (ASF.Applications.VIEW_DIR); Path : constant String := Dir & Name; begin if Kind (Path) /= Directory then Ada.Text_IO.Put_Line ("Cannot read model directory: " & Path); end if; Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare File_Path : constant String := Full_Name (Ent); begin H.Generate (Mode, File_Path); end; end loop; exception when Ada.IO_Exceptions.Name_Error => H.Error ("Template directory {0} does not exist", Path); end Generate_All; end Gen.Generator;
Store the model bean in a request mockup object
Store the model bean in a request mockup object
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
f02a5c22f3a54d49b93934c0855c741961421541
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Questions.Services; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Question_Service_Access := Bean.Module.Get_Question_Manager; begin Manager.Save_Question (Bean); end Save; procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Question_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with AWA.Services.Contexts; with AWA.Questions.Services; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Question_Service_Access := Bean.Module.Get_Question_Manager; begin Manager.Save_Question (Bean); end Save; procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Question_Bean; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; end AWA.Questions.Beans;
Implement Create_Question_List_Bean
Implement Create_Question_List_Bean
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
b6fa1c0bad2dbe8724feaa47498c2977588ecffa
regtests/util-streams-buffered-lzma-tests.adb
regtests/util-streams-buffered-lzma-tests.adb
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams -- Copyright (C) 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.AES; with Util.Encoders.AES; with Ada.Streams.Stream_IO; package body Util.Streams.Buffered.Lzma.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; procedure Test_Stream_File (T : in out Test; Item : in String; Count : in Positive; Encrypt : in Boolean; Mode : in Util.Encoders.AES.AES_Mode; Label : in String); package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write", Test_Compress_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)", Test_Compress_File_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Read+Write", Test_Compress_Decompress_Stream'Access); end Add_Tests; procedure Test_Compress_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("test-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma"); begin Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Access, Size => 1024); Print.Initialize (Output => Buffer'Access, Size => 5); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_Stream; procedure Test_Compress_File_Stream (T : in out Test) is Stream : aliased File_Stream; In_Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Path : constant String := Util.Tests.Get_Test_Path ("test-big-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma"); begin In_Stream.Open (Ada.Streams.Stream_IO.In_File, Util.Tests.Get_Path ("regtests/files/test-big-stream.bin")); Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Access, Size => 32768); Util.Streams.Copy (From => In_Stream, Into => Buffer); Buffer.Flush; Buffer.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_File_Stream; procedure Test_Stream_File (T : in out Test; Item : in String; Count : in Positive; Encrypt : in Boolean; Mode : in Util.Encoders.AES.AES_Mode; Label : in String) is use Ada.Strings.Unbounded; Path : constant String := Util.Tests.Get_Test_Path ("stream-lzma-aes-" & Label & ".aes"); Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("0123456789abcdef0123456789abcdef"); File : aliased File_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Compress : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Decompress : aliased Util.Streams.Buffered.Lzma.Decompress_Stream; Print : Util.Streams.Texts.Print_Stream; Reader : Util.Streams.Texts.Reader_Stream; begin -- Print -> Compress -> Cipher -> File File.Create (Mode => Out_File, Name => Path); if Encrypt then Cipher.Produces (File'Access, 64); Cipher.Set_Key (Key, Mode); Compress.Initialize (Cipher'Access, 1024); else Compress.Initialize (File'Access, 1024); end if; Print.Initialize (Compress'Access); for I in 1 .. Count loop Print.Write (Item & ASCII.LF); end loop; Print.Close; -- File -> Decipher -> Decompress -> Reader File.Open (Mode => In_File, Name => Path); if Encrypt then Decipher.Consumes (File'Access, 128); Decipher.Set_Key (Key, Mode); Decompress.Initialize (Decipher'Access, 1024); else Decompress.Initialize (File'Access, 1024); end if; Reader.Initialize (From => Decompress'Access); declare Line_Count : Natural := 0; begin while not Reader.Is_Eof loop declare Line : Unbounded_String; begin Reader.Read_Line (Line); exit when Length (Line) = 0; if Item & ASCII.LF /= Line then Util.Tests.Assert_Equals (T, Item & ASCII.LF, To_String (Line)); end if; Line_Count := Line_Count + 1; end; end loop; File.Close; Util.Tests.Assert_Equals (T, Count, Line_Count); end; end Test_Stream_File; procedure Test_Compress_Decompress_Stream (T : in out Test) is begin Test_Stream_File (T, "abcdefgh", 1000, False, Util.Encoders.AES.CBC, "AES-CBC"); end Test_Compress_Decompress_Stream; end Util.Streams.Buffered.Lzma.Tests;
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams -- Copyright (C) 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Util.Streams.AES; with Util.Encoders.AES; with Ada.Streams.Stream_IO; package body Util.Streams.Buffered.Lzma.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; procedure Test_Stream_File (T : in out Test; Item : in String; Count : in Positive; Encrypt : in Boolean; Mode : in Util.Encoders.AES.AES_Mode; Label : in String); package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write", Test_Compress_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)", Test_Compress_File_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Read+Write", Test_Compress_Decompress_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Read+Write+AES-CBC", Test_Compress_Encrypt_Decompress_Decrypt_Stream'Access); end Add_Tests; procedure Test_Compress_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("test-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma"); begin Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Access, Size => 1024); Print.Initialize (Output => Buffer'Access, Size => 5); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_Stream; procedure Test_Compress_File_Stream (T : in out Test) is Stream : aliased File_Stream; In_Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Path : constant String := Util.Tests.Get_Test_Path ("test-big-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma"); begin In_Stream.Open (Ada.Streams.Stream_IO.In_File, Util.Tests.Get_Path ("regtests/files/test-big-stream.bin")); Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Access, Size => 32768); Util.Streams.Copy (From => In_Stream, Into => Buffer); Buffer.Flush; Buffer.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_File_Stream; procedure Test_Stream_File (T : in out Test; Item : in String; Count : in Positive; Encrypt : in Boolean; Mode : in Util.Encoders.AES.AES_Mode; Label : in String) is use Ada.Strings.Unbounded; Path : constant String := Util.Tests.Get_Test_Path ("stream-lzma-aes-" & Label & ".aes"); Key : constant Util.Encoders.Secret_Key := Util.Encoders.Create ("0123456789abcdef0123456789abcdef"); File : aliased File_Stream; Decipher : aliased Util.Streams.AES.Decoding_Stream; Cipher : aliased Util.Streams.AES.Encoding_Stream; Compress : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Decompress : aliased Util.Streams.Buffered.Lzma.Decompress_Stream; Print : Util.Streams.Texts.Print_Stream; Reader : Util.Streams.Texts.Reader_Stream; begin -- Print -> Compress -> Cipher -> File File.Create (Mode => Out_File, Name => Path); if Encrypt then Cipher.Produces (File'Access, 64); Cipher.Set_Key (Key, Mode); Compress.Initialize (Cipher'Access, 1024); else Compress.Initialize (File'Access, 1024); end if; Print.Initialize (Compress'Access); for I in 1 .. Count loop Print.Write (Item & ASCII.LF); end loop; Print.Close; -- File -> Decipher -> Decompress -> Reader File.Open (Mode => In_File, Name => Path); if Encrypt then Decipher.Consumes (File'Access, 128); Decipher.Set_Key (Key, Mode); Decompress.Initialize (Decipher'Access, 1024); else Decompress.Initialize (File'Access, 1024); end if; Reader.Initialize (From => Decompress'Access); declare Line_Count : Natural := 0; begin while not Reader.Is_Eof loop declare Line : Unbounded_String; begin Reader.Read_Line (Line); exit when Length (Line) = 0; if Item & ASCII.LF /= Line then Util.Tests.Assert_Equals (T, Item & ASCII.LF, To_String (Line)); end if; Line_Count := Line_Count + 1; end; end loop; File.Close; Util.Tests.Assert_Equals (T, Count, Line_Count); end; end Test_Stream_File; procedure Test_Compress_Decompress_Stream (T : in out Test) is begin Test_Stream_File (T, "abcdefgh", 1000, False, Util.Encoders.AES.CBC, "NONE"); end Test_Compress_Decompress_Stream; procedure Test_Compress_Encrypt_Decompress_Decrypt_Stream (T : in out Test) is begin Test_Stream_File (T, "abcdefgh", 1000, True, Util.Encoders.AES.CBC, "AES-CBC"); end Test_Compress_Encrypt_Decompress_Decrypt_Stream; end Util.Streams.Buffered.Lzma.Tests;
Add Test_Compress_Encrypt_Decompress_Decrypt_Stream and register it for execution
Add Test_Compress_Encrypt_Decompress_Decrypt_Stream and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4e884668801d6d2fba5dc8ffdf1cd02f98c8dec1
awa/src/awa-users-services.ads
awa/src/awa-users-services.ads
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Modules; with AWA.Events; with Security.Auth; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the email address. function Get_Password_Hash (Model : in User_Service; Password : in String; Email : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- to the user in an email. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Users.Services;
----------------------------------------------------------------------- -- awa.users -- User registration, authentication processes -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with AWA.Users.Models; with AWA.Users.Principals; with AWA.Modules; with AWA.Events; with Security.Auth; with Security.Random; with ADO; with ADO.Sessions; -- == Introduction == -- The *users* module provides a *users* service which controls the user data model. -- -- == Events == -- The *users* module exposes a number of events which are posted when some action -- are performed at the service level. -- -- === user-register === -- This event is posted when a new user is registered in the application. -- It can be used to send a registration email. -- -- === user-create === -- This event is posted when a new user is created. It can be used to trigger -- the pre-initialization of the application for the new user. -- -- === user-lost-password === -- This event is posted when a user asks for a password reset through an -- anonymous form. It is intended to be used to send the reset password email. -- -- === user-reset-password === -- This event is posted when a user has successfully reset his password. -- It can be used to send an email. -- package AWA.Users.Services is use AWA.Users.Models; package User_Create_Event is new AWA.Events.Definition (Name => "user-create"); package User_Register_Event is new AWA.Events.Definition (Name => "user-register"); package User_Lost_Password_Event is new AWA.Events.Definition (Name => "user-lost-password"); package User_Reset_Password_Event is new AWA.Events.Definition (Name => "user-reset-password"); NAME : constant String := "User_Service"; Not_Found : exception; User_Exist : exception; -- The session is an authenticate session. The user authenticated using password or OpenID. -- When the user logout, this session is closed as well as any connection session linked to -- the authenticate session. AUTH_SESSION_TYPE : constant Integer := 1; -- The session is a connection session. It is linked to an authenticate session. -- This session can be closed automatically due to a timeout or user's inactivity. -- The AID cookie refers to this connection session to create a new connection session. -- Once re-connecting is done, the connection session refered to by AID is marked -- as <b<USED_SESSION_TYPE</b> and a new AID cookie with the new connection session is -- returned to the user. CONNECT_SESSION_TYPE : constant Integer := 0; -- The session is a connection session whose associated AID cookie has been used. -- This session cannot be used to re-connect a user through the AID cookie. USED_SESSION_TYPE : constant Integer := 2; -- Get the user name from the email address. -- Returns the possible user name from his email address. function Get_Name_From_Email (Email : in String) return String; type User_Service is new AWA.Modules.Module_Manager with private; type User_Service_Access is access all User_Service'Class; -- Build the authenticate cookie. The cookie is signed using HMAC-SHA1 with a private key. function Get_Authenticate_Cookie (Model : in User_Service; Id : in ADO.Identifier) return String; -- Get the authenticate identifier from the cookie. -- Verify that the cookie is valid, the signature is correct. -- Returns the identified or NO_IDENTIFIER function Get_Authenticate_Id (Model : in User_Service; Cookie : in String) return ADO.Identifier; -- Get the password hash. The password is signed using HMAC-SHA1 with the salt. function Get_Password_Hash (Model : in User_Service; Password : in String; Salt : in String) return String; -- Create a user in the database with the given user information and -- the associated email address. Verify that no such user already exist. -- Raises User_Exist exception if a user with such email is already registered. procedure Create_User (Model : in out User_Service; User : in out User_Ref'Class; Email : in out Email_Ref'Class); -- Verify the access key and retrieve the user associated with that key. -- Starts a new session associated with the given IP address. -- The authenticated user is identified by a principal instance allocated -- and returned in <b>Principal</b>. -- Raises Not_Found if the access key does not exist. procedure Verify_User (Model : in User_Service; Key : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his email address and his password. -- If the user is authenticated, return the user information and -- create a new session. The IP address of the connection is saved -- in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Email : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with his OpenID identifier. The authentication process -- was made by an external OpenID provider. If the user does not yet exists in -- the database, a record is created for him. Create a new session for the user. -- The IP address of the connection is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Auth : in Security.Auth.Authentication; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Authenticate the user with the authenticate cookie generated from a previous authenticate -- session. If the cookie has the correct signature, matches a valid session, -- return the user information and create a new session. The IP address of the connection -- is saved in the session. -- Raises Not_Found exception if the user is not recognized procedure Authenticate (Model : in User_Service; Cookie : in String; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Start the lost password process for a user. Find the user having -- the given email address and send that user a password reset key -- in an email. -- Raises Not_Found exception if no user with such email exist procedure Lost_Password (Model : in out User_Service; Email : in String); -- Reset the password of the user associated with the secure key. -- Raises Not_Found if there is no key or if the user does not have any email procedure Reset_Password (Model : in out User_Service; Key : in String; Password : in String; IpAddr : in String; Principal : out AWA.Users.Principals.Principal_Access); -- Verify that the user session identified by <b>Id</b> is valid and still active. -- Returns the user and the session objects. -- Raises Not_Found if the session does not exist or was closed. procedure Verify_Session (Model : in User_Service; Id : in ADO.Identifier; User : out User_Ref'Class; Session : out Session_Ref'Class); -- Closes the session identified by <b>Id</b>. The session identified should refer to -- a valid and not closed connection session. -- When <b>Logout</b> is set, the authenticate session is also closed. The connection -- sessions associated with the authenticate session are also closed. -- Raises <b>Not_Found</b> if the session is invalid or already closed. procedure Close_Session (Model : in User_Service; Id : in ADO.Identifier; Logout : in Boolean := False); procedure Send_Alert (Model : in User_Service; Kind : in AWA.Events.Event_Index; User : in User_Ref'Class; Props : in out AWA.Events.Module_Event); -- Initialize the user service. overriding procedure Initialize (Model : in out User_Service; Module : in AWA.Modules.Module'Class); private function Create_Key (Model : in out User_Service; Number : in ADO.Identifier) return String; procedure Create_Session (Model : in User_Service; DB : in out ADO.Sessions.Master_Session; Session : out Session_Ref'Class; User : in User_Ref'Class; Ip_Addr : in String; Principal : out AWA.Users.Principals.Principal_Access); type User_Service is new AWA.Modules.Module_Manager with record Server_Id : Integer := 0; Random : Security.Random.Generator; Auth_Key : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Users.Services;
Use the Security.Random package for the random key and salt generation Change Create_User, Lost_Password and Reset_Password for in out parameter Declare the Create_Key operation for the generation and secure HMAC key
Use the Security.Random package for the random key and salt generation Change Create_User, Lost_Password and Reset_Password for in out parameter Declare the Create_Key operation for the generation and secure HMAC key
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
14af9c30e242002b0dea35f3e6ec9db60fa082aa
mat/src/mat-targets-probes.ads
mat/src/mat-targets-probes.ads
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Process : Target_Process_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in out Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type_Access); private procedure Probe_Begin (Probe : in out Process_Probe_Type; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message); end MAT.Targets.Probes;
----------------------------------------------------------------------- -- mat-targets-probes - Definition and Analysis of process start events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Events; with MAT.Events.Targets; with MAT.Events.Probes; package MAT.Targets.Probes is type Process_Probe_Type is new MAT.Events.Probes.Probe_Type with record Target : Target_Type_Access; Manager : MAT.Events.Probes.Probe_Manager_Type_Access; Process : Target_Process_Type_Access; Events : MAT.Events.Targets.Target_Events_Access; end record; type Process_Probe_Type_Access is access all Process_Probe_Type'Class; -- Create a new process after the begin event is received from the event stream. procedure Create_Process (Probe : in out Process_Probe_Type; Pid : in MAT.Types.Target_Process_Ref; Path : in Ada.Strings.Unbounded.Unbounded_String); -- Extract the probe information from the message. overriding procedure Extract (Probe : in Process_Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out MAT.Events.Targets.Probe_Event_Type); procedure Execute (Probe : in Process_Probe_Type; Event : in MAT.Events.Targets.Probe_Event_Type); -- Register the reader to extract and analyze process events. procedure Register (Into : in out MAT.Events.Probes.Probe_Manager_Type'Class; Probe : in Process_Probe_Type_Access); -- Initialize the target object to prepare for reading process events. procedure Initialize (Target : in out Target_Type; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class); private procedure Probe_Begin (Probe : in out Process_Probe_Type; Id : in MAT.Events.Internal_Reference; Defs : in MAT.Events.Attribute_Table; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message); end MAT.Targets.Probes;
Fix the Initialize procedure parameter
Fix the Initialize procedure parameter
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6e78ee975b11f1cd736ed0a179d93463921a9a9f
matp/src/frames/mat-frames.adb
matp/src/frames/mat-frames.adb
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body MAT.Frames is use type MAT.Types.Target_Addr; procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Frames.Targets"); procedure Split (F : in out Frame_Type; Pos : in Positive); procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); -- Get the root frame object. function Get_Root (Frame : in Frame_Type) return Frame_Type; function Check (Frame : in Frame_Type) return Boolean; function Check (Frame : in Frame_Type) return Boolean is Child : Frame_Type; Result : Boolean := True; begin if Frame = null then return False; end if; Child := Frame.Children; while Child /= null loop if Child.Parent /= Frame then Log.Error ("Invalid parent link"); Result := False; end if; if Child.Children /= null and then not Check (Child) then Log.Error ("A child is now invalid"); Result := False; end if; Child := Child.Next; end loop; return Result; end Check; -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Get the root frame object. -- ------------------------------ function Get_Root (Frame : in Frame_Type) return Frame_Type is Parent : Frame_Type := Frame; begin loop if Parent.Parent = null then return Parent; end if; Parent := Parent.Parent; end loop; end Get_Root; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value. -- ------------------------------ function Backtrace (Frame : in Frame_Type; Max_Level : in Natural := 0) return Frame_Table is Length : Natural; begin if Max_Level > 0 and Max_Level < Frame.Depth then Length := Max_Level; else Length := Frame.Depth; end if; declare Current : Frame_Type := Frame; Pos : Natural := Length; New_Pos : Natural; Pc : Frame_Table (1 .. Length); begin while Current /= null and Pos /= 0 loop if Pos >= Current.Local_Depth then New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; else Pc (1 .. Pos) := Current.Calls (Current.Local_Depth - Pos + 1 .. Current.Local_Depth); Pos := 0; end if; Current := Current.Parent; end loop; return Pc; end; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : constant Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Destroy (F); end loop; -- Unlink from parent list. if Frame.Parent /= null then F := Frame.Parent.Children; if F = Frame then Frame.Parent.Children := Frame.Next; else while F /= null and then F.Next /= Frame loop F := F.Next; end loop; if F = null then -- Log.Error ("Frame is not linked to the correct parent"); -- if not Check (Get_Root (Frame)) then -- Log.Error ("Check failed"); -- else -- Log.Error ("Check is ok"); -- end if; -- MAT.Frames.Print (Ada.Text_IO.Standard_Output, Get_Root (Frame)); return; else F.Next := Frame.Next; end if; end if; end if; -- Free (Frame); end Destroy; -- ------------------------------ -- Release the frame when its reference is no longer necessary. -- ------------------------------ procedure Release (Frame : in Frame_Type) is Current : Frame_Type := Frame; begin -- Scan the frame until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Type := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; -- if not Check (Get_Root (Frame)) then -- Log.Error ("Frame is invalid"); -- end if; end Release; -- ------------------------------ -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. -- ------------------------------ procedure Split (F : in out Frame_Type; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : constant Frame_Type := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used - 1, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Type := F.Parent.Children; begin Log.Debug ("Split frame"); -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; F.Used := 1; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; -- if not Check (Get_Root (F)) then -- Log.Error ("Error when splitting frame"); -- end if; end Split; procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Child : Frame_Type := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; -- if not Check (Get_Root (Child)) then -- Log.Error ("Error when adding frame"); -- end if; end loop; Result := Child; end Add_Frame; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Current : Frame_Type := Frame; Child : Frame_Type; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : MAT.Types.Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else Current.Used := Current.Used + 1; if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Current.Used := Current.Used + 1; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current.Used := Current.Used + 1; Current := Child; Lpos := 2; Pos := Pos + 1; end if; end loop; Current.Used := Current.Used + 1; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type is Child : Frame_Type := Frame.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in Frame_Table) return Frame_Type is Child : Frame_Type := Frame; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ procedure Find (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type; Last_Pc : out Natural) is Current : Frame_Type := Frame; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search : while Pos <= Pc'Last loop declare Addr : constant MAT.Types.Target_Addr := Pc (Pos); Child : Frame_Type := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; -- ------------------------------ -- Check whether the frame contains a call to the function described by the address range. -- ------------------------------ function In_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean is Current : Frame_Type := Frame; begin while Current /= null loop for I in 1 .. Current.Local_Depth loop if Current.Calls (I) >= From and Current.Calls (I) <= To then return True; end if; end loop; Current := Current.Parent; end loop; return False; end In_Function; -- ------------------------------ -- Check whether the inner most frame contains a call to the function described by -- the address range. This function looks only at the inner most frame and not the -- whole stack frame. -- ------------------------------ function By_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean is Pc : MAT.Types.Target_Addr; begin if Frame /= null then Pc := Frame.Calls (Frame.Local_Depth); if Pc >= From and Pc <= To then return True; end if; end if; return False; end By_Function; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Containers.Ordered_Maps; with System; with Util.Log.Loggers; package body MAT.Frames is use type MAT.Types.Target_Addr; procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Frames.Targets"); procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); -- Get the root frame object. function Get_Root (Frame : in Frame_Type) return Frame_Type; function Check (Frame : in Frame_Type) return Boolean; function Check (Frame : in Frame_Type) return Boolean is Child : Frame_Type; Result : Boolean := True; begin if Frame = null then return False; end if; Child := Frame.Children; while Child /= null loop if Child.Parent /= Frame then Log.Error ("Invalid parent link"); Result := False; end if; if Child.Children /= null and then not Check (Child) then Log.Error ("A child is now invalid"); Result := False; end if; Child := Child.Next; end loop; return Result; end Check; -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Get the root frame object. -- ------------------------------ function Get_Root (Frame : in Frame_Type) return Frame_Type is Parent : Frame_Type := Frame; begin loop if Parent.Parent = null then return Parent; end if; Parent := Parent.Parent; end loop; end Get_Root; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value. -- ------------------------------ function Backtrace (Frame : in Frame_Type; Max_Level : in Natural := 0) return Frame_Table is Length : Natural; begin if Max_Level > 0 and Max_Level < Frame.Depth then Length := Max_Level; else Length := Frame.Depth; end if; declare Current : Frame_Type := Frame; Pos : Natural := Length; Pc : Frame_Table (1 .. Length); begin while Current /= null and Pos /= 0 loop Pc (Pos) := Current.Pc; Pos := Pos - 1; Current := Current.Parent; end loop; return Pc; end; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : constant Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Pc; Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame '(Parent => null, Depth => 0, Pc => 0, others => <>); end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Frame.Children := F.Next; Destroy (F); end loop; Free (Frame); end Destroy; procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Child : Frame_Type := F.Children; Parent : Frame_Type := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; begin while Pos <= Pc'Last loop Current_Depth := Current_Depth + 1; Child := new Frame '(Parent => Parent, Next => Child, Children => null, Used => 1, Depth => Current_Depth, Pc => Pc (Pos)); Pos := Pos + 1; Parent.Children := Child; Parent := Child; Child := null; end loop; Result := Parent; end Add_Frame; function "<" (Left, Right : in Frame_Type) return Boolean; function "<" (Left, Right : in Frame_Type) return Boolean is use type System.Address; begin return Left.all'Address < Right.all'Address; end "<"; type Frame_Table_Access is access all Frame_Table; package Check_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Frame_Type, Element_Type => Frame_Table_Access, "<" => "<", "=" => "="); Map : Check_Maps.Map; procedure Verify_Frames is Iter : Check_Maps.Cursor := Map.First; begin Log.Info ("There are {0} frames in the map", Natural'Image (Natural (Map.Length))); while Check_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Addr; Frame : constant Frame_Type := Check_Maps.Key (Iter); Table : constant Frame_Table_Access := Check_Maps.Element (Iter); Pc : constant Frame_Table := Backtrace (Frame); begin if Table'Length /= Pc'Length then Log.Error ("Invalid frame length"); end if; for I in Pc'Range loop if Table (I) /= Pc (I) then Log.Error ("Frame at {0} is different", Natural'Image (I)); end if; end loop; end; Check_Maps.Next (Iter); end loop; end Verify_Frames; procedure Add_Frame (Frame : in Frame_Type; Pc : in Frame_Table) is begin if not Map.Contains (Frame) then declare Table : Frame_Table_Access := new Frame_Table '(Pc); begin Map.Include (Frame, Table); end; -- else -- declare -- Iter : Check_Maps.Cursor := Map.First; -- begin -- while Check_Maps.Has_Element (Iter) loop -- declare -- use type MAT.Types.Target_Addr; -- -- F : Frame_Type := Check_Maps.Key (Iter); -- Table : constant Frame_Table_Access := Check_Maps.Element (Iter); -- Found : Boolean := True; -- begin -- if F /= Frame and Table'Length = Pc'Length then -- for I in Pc'Range loop -- if Table (I) /= Pc (I) then -- Found := False; -- exit; -- end if; -- end loop; -- if Found then -- Log.Error ("Stack frame is already inserted by a new Frame is returned"); -- end if; -- end if; -- end; -- Check_Maps.Next (Iter); -- end loop; -- end; end if; -- Verify_Frames; end Add_Frame; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Parent : Frame_Type := Frame; Current : Frame_Type := Frame.Children; Pos : Positive := Pc'First; Addr : MAT.Types.Target_Addr; begin if Pc'Length = 0 then Result := Frame; Frame.Used := Frame.Used + 1; return; end if; if Current = null then Add_Frame (Frame, Pc, Result); Add_Frame (Result, Pc); return; end if; Addr := Pc (Pos); loop if Addr = Current.Pc then Current.Used := Current.Used + 1; Pos := Pos + 1; if Pos > Pc'Last then Result := Current; Add_Frame (Result, Pc); return; end if; if Current.Children = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); Add_Frame (Result, Pc); return; end if; Parent := Current; Current := Current.Children; Addr := Pc (Pos); elsif Current.Next = null then Add_Frame (Parent, Pc (Pos .. Pc'Last), Result); Add_Frame (Result, Pc); return; else Current := Current.Next; end if; end loop; end Insert; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type is Child : Frame_Type := Frame.Children; begin while Child /= null loop if Child.Pc = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ -- function Find (Frame : in Frame_Type; -- Pc : in Frame_Table) return Frame_Type is -- Child : Frame_Type := Frame; -- Pos : Positive := Pc'First; -- begin -- while Pos <= Pc'Last loop -- Child := Find (Child, Pc (Pos)); -- Pos := Pos + 1; -- -- All the PC of the child frame must match. -- while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop -- if Child.Calls (Lpos) /= Pc (Pos) then -- raise Not_Found; -- end if; -- Lpos := Lpos + 1; -- Pos := Pos + 1; -- end loop; -- end loop; -- return Child; -- end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- -- ------------------------------ -- procedure Find (Frame : in Frame_Type; -- Pc : in Frame_Table; -- Result : out Frame_Type; -- Last_Pc : out Natural) is -- Current : Frame_Type := Frame; -- Pos : Positive := Pc'First; -- Lpos : Positive; -- begin -- Main_Search : -- while Pos <= Pc'Last loop -- declare -- Addr : constant MAT.Types.Target_Addr := Pc (Pos); -- Child : Frame_Type := Current.Children; -- begin -- -- Find the child which has the corresponding PC. -- loop -- exit Main_Search when Child = null; -- exit when Child.Pc = Addr; -- Child := Child.Next; -- end loop; -- -- Current := Child; -- Pos := Pos + 1; -- Lpos := 2; -- -- All the PC of the child frame must match. -- while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop -- exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); -- Lpos := Lpos + 1; -- Pos := Pos + 1; -- end loop; -- end; -- end loop Main_Search; -- Result := Current; -- if Pos > Pc'Last then -- Last_Pc := 0; -- else -- Last_Pc := Pos; -- end if; -- end Find; -- ------------------------------ -- Check whether the frame contains a call to the function described by the address range. -- ------------------------------ function In_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean is Current : Frame_Type := Frame; begin while Current /= null loop if Current.Pc >= From and Current.Pc <= To then return True; end if; Current := Current.Parent; end loop; return False; end In_Function; -- ------------------------------ -- Check whether the inner most frame contains a call to the function described by -- the address range. This function looks only at the inner most frame and not the -- whole stack frame. -- ------------------------------ function By_Function (Frame : in Frame_Type; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr) return Boolean is begin return Frame /= null and then Frame.Pc >= From and then Frame.Pc <= To; end By_Function; end MAT.Frames;
Refactor the frames implementation - Remove the Split operation - Update the Insert, Add_Frame, Backtrace operation to store a single PC per Frame record - Remove/comment out unused operations - Add some debugging/verification code
Refactor the frames implementation - Remove the Split operation - Update the Insert, Add_Frame, Backtrace operation to store a single PC per Frame record - Remove/comment out unused operations - Add some debugging/verification code
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1536866909cc3d70b9c309ee22869f87e11d887b
awa/src/awa-commands-drivers.adb
awa/src/awa-commands-drivers.adb
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- Copyright (C) 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Util.Strings.Formats; with Servlet.Core; package body AWA.Commands.Drivers is use Ada.Strings.Unbounded; use AWA.Applications; function "-" (Message : in String) return String is (Message); function Format (Message : in String; Arg1 : in String) return String renames Util.Strings.Formats.Format; Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Command.Application_Name'Access, Switch => "-a:", Long_Switch => "--application=", Argument => "NAME", Help => -("Defines the name or URI of the application")); AWA.Commands.Setup_Command (Config, Context); end Setup; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean is begin return Command.Application_Name.all = URI; end Is_Application; overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; App_Name : Unbounded_String; procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if Command.Is_Application (URI) then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; elsif Command.Application_Name'Length = 0 then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin WS.Iterate (Find'Access); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Configure (To_String (App_Name), Context); if Command.Initialize_Application then Selected.Initialize (Context.App_Config, Context.Factory); end if; Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context); end Execute; -- ------------------------------ -- Print the command usage. -- ------------------------------ procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin GC.Display_Help (Context.Command_Config); if Name'Length > 0 then Driver.Usage (Args, Context, Name); end if; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; -- ------------------------------ -- Execute the command with its arguments. -- ------------------------------ procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Driver.Execute (Name, Args, Context); end Execute; -- ------------------------------ -- Get the server configuration file path. -- ------------------------------ function Get_Configuration_Path (Context : in out Context_Type) return String is begin if Context.Config_File'Length = 0 then return Driver_Name & ".properties"; else return Context.Config_File.all; end if; end Get_Configuration_Path; procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List) is begin GC.Set_Usage (Config => Context.Command_Config, Usage => "[switchs] command [arguments]", Help => Format (-("{0} - server commands"), Driver_Name)); GC.Getopt (Config => Context.Command_Config); Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument); if Context.Debug or else Context.Verbose or else Context.Dump then Configure_Logs (Root => Context.Global_Config.Get ("log4j.rootCategory", ""), Debug => Context.Debug, Dump => Context.Dump, Verbose => Context.Verbose); end if; Context.Load_Configuration (Get_Configuration_Path (Context)); declare Cmd_Name : constant String := Arguments.Get_Command_Name; begin if Cmd_Name'Length = 0 then Context.Console.Notice (N_ERROR, -("Missing command name to execute.")); Usage (Arguments, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Execute (Cmd_Name, Arguments, Context); exception when GNAT.Command_Line.Invalid_Parameter => Context.Console.Notice (N_ERROR, -("Missing option parameter")); raise Error; end; end Run; begin Driver.Add_Command ("help", -("print some help"), Help_Command'Access); end AWA.Commands.Drivers;
----------------------------------------------------------------------- -- awa-commands-drivers -- Driver for AWA commands for server or admin tool -- Copyright (C) 2020, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Command_Line; with Util.Strings.Formats; with Servlet.Core; package body AWA.Commands.Drivers is use Ada.Strings.Unbounded; use AWA.Applications; function "-" (Message : in String) return String is (Message); function Format (Message : in String; Arg1 : in String) return String renames Util.Strings.Formats.Format; Help_Command : aliased AWA.Commands.Drivers.Help_Command_Type; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Set_Usage (Config => Config, Usage => Command.Get_Name & " [arguments]", Help => Command.Get_Description); AWA.Commands.Setup_Command (Config, Context); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin null; end Help; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ overriding procedure Setup (Command : in out Application_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Command.Application_Name'Access, Switch => "-a:", Long_Switch => "--application=", Argument => "NAME", Help => -("Defines the name or URI of the application")); AWA.Commands.Setup_Command (Config, Context); end Setup; function Is_Application (Command : in Application_Command_Type; URI : in String) return Boolean is begin return Command.Application_Name.all = Uri or else (Uri (Uri'First) = '/' and then Command.Application_Name.all = Uri (Uri'First + 1 .. Uri'Last)); end Is_Application; overriding procedure Execute (Command : in out Application_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; App_Name : Unbounded_String; procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin if App.all in Application'Class then if Command.Is_Application (URI) then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; elsif Command.Application_Name'Length = 0 then App_Name := To_Unbounded_String (URI (URI'First + 1 .. URI'Last)); Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin WS.Iterate (Find'Access); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Configure (To_String (App_Name), Context); if Command.Initialize_Application then Selected.Initialize (Context.App_Config, Context.Factory); end if; Application_Command_Type'Class (Command).Execute (Selected.all, Args, Context); end Execute; -- ------------------------------ -- Print the command usage. -- ------------------------------ procedure Usage (Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin GC.Display_Help (Context.Command_Config); if Name'Length > 0 then Driver.Usage (Args, Context, Name); end if; Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; -- ------------------------------ -- Execute the command with its arguments. -- ------------------------------ procedure Execute (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Driver.Execute (Name, Args, Context); end Execute; -- ------------------------------ -- Get the server configuration file path. -- ------------------------------ function Get_Configuration_Path (Context : in out Context_Type) return String is begin if Context.Config_File'Length = 0 then return Driver_Name & ".properties"; else return Context.Config_File.all; end if; end Get_Configuration_Path; procedure Run (Context : in out Context_Type; Arguments : out Util.Commands.Dynamic_Argument_List) is begin GC.Set_Usage (Config => Context.Command_Config, Usage => "[switchs] command [arguments]", Help => Format (-("{0} - server commands"), Driver_Name)); GC.Getopt (Config => Context.Command_Config); Util.Commands.Parsers.GNAT_Parser.Get_Arguments (Arguments, GC.Get_Argument); if Context.Debug or else Context.Verbose or else Context.Dump then Configure_Logs (Root => Context.Global_Config.Get ("log4j.rootCategory", ""), Debug => Context.Debug, Dump => Context.Dump, Verbose => Context.Verbose); end if; Context.Load_Configuration (Get_Configuration_Path (Context)); declare Cmd_Name : constant String := Arguments.Get_Command_Name; begin if Cmd_Name'Length = 0 then Context.Console.Notice (N_ERROR, -("Missing command name to execute.")); Usage (Arguments, Context); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; Execute (Cmd_Name, Arguments, Context); exception when GNAT.Command_Line.Invalid_Parameter => Context.Console.Notice (N_ERROR, -("Missing option parameter")); raise Error; end; end Run; begin Driver.Add_Command ("help", -("print some help"), Help_Command'Access); end AWA.Commands.Drivers;
Fix #33: ignore a possible / at beginning of application name
Fix #33: ignore a possible / at beginning of application name
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
7adf8832f6b0baf5939e4574b2627d17200063be
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 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;
----------------------------------------------------------------------- -- 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;
Remove Has_Role operation
Remove Has_Role operation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b8c36bd25ec175617f3377707008c64f1c968a7b
src/sys/streams/util-streams-pipes.ads
src/sys/streams/util-streams-pipes.ads
----------------------------------------------------------------------- -- util-streams-pipes -- Pipe stream to or from a process -- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Processes; -- == Pipes == -- The `Util.Streams.Pipes` package defines a pipe stream to or from a process. -- It allows to launch an external program while getting the program standard output or -- providing the program standard input. The `Pipe_Stream` type represents the input or -- output stream for the external program. This is a portable interface that works on -- Unix and Windows. -- -- The process is created and launched by the `Open` operation. The pipe allows -- to read or write to the process through the `Read` and `Write` operation. -- It is very close to the *popen* operation provided by the C stdio library. -- First, create the pipe instance: -- -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- -- The pipe instance can be associated with only one process at a time. -- The process is launched by using the `Open` command and by specifying the command -- to execute as well as the pipe redirection mode: -- -- * `READ` to read the process standard output, -- * `WRITE` to write the process standard input. -- -- For example to run the `ls -l` command and read its output, we could run it by using: -- -- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ); -- -- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the -- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads -- the pipe to fill the buffer. The initialization of the buffer is the following: -- -- with Util.Streams.Buffered; -- ... -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Access, Size => 1024); -- -- And to read the process output, one can use the following: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- ... -- Buffer.Read (Into => Content); -- -- The pipe object should be closed when reading or writing to it is finished. -- By closing the pipe, the caller will wait for the termination of the process. -- The process exit status can be obtained by using the `Get_Exit_Status` function. -- -- Pipe.Close; -- if Pipe.Get_Exit_Status /= 0 then -- Ada.Text_IO.Put_Line ("Command exited with status " -- & Integer'Image (Pipe.Get_Exit_Status)); -- end if; -- -- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied. -- When leaving the scope of the `Pipe_Stream` instance, the application will wait for -- the process to terminate. -- -- Before opening the pipe, it is possible to have some control on the process that -- will be created to configure: -- -- * The shell that will be used to launch the process, -- * The process working directory, -- * Redirect the process output to a file, -- * Redirect the process error to a file, -- * Redirect the process input from a file. -- -- All these operations must be made before calling the `Open` procedure. package Util.Streams.Pipes is use Util.Processes; subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE; -- ----------------------- -- Pipe stream -- ----------------------- -- The <b>Pipe_Stream</b> is an output/input stream that reads or writes -- to or from a process. type Pipe_Stream is limited new Output_Stream and Input_Stream with private; -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. procedure Set_Shell (Stream : in out Pipe_Stream; Shell : in String); -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. procedure Set_Working_Directory (Stream : in out Pipe_Stream; Path : in String); -- Closes the given file descriptor in the child process before executing the command. procedure Add_Close (Stream : in out Pipe_Stream; Fd : in Util.Processes.File_Type); -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ); -- Close the pipe and wait for the external process to terminate. overriding procedure Close (Stream : in out Pipe_Stream); -- Get the process exit status. function Get_Exit_Status (Stream : in Pipe_Stream) return Integer; -- Returns True if the process is running. function Is_Running (Stream : in Pipe_Stream) return Boolean; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record Proc : Util.Processes.Process; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Pipe_Stream); end Util.Streams.Pipes;
----------------------------------------------------------------------- -- util-streams-pipes -- Pipe stream to or from a process -- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; -- == Pipes == -- The `Util.Streams.Pipes` package defines a pipe stream to or from a process. -- It allows to launch an external program while getting the program standard output or -- providing the program standard input. The `Pipe_Stream` type represents the input or -- output stream for the external program. This is a portable interface that works on -- Unix and Windows. -- -- The process is created and launched by the `Open` operation. The pipe allows -- to read or write to the process through the `Read` and `Write` operation. -- It is very close to the *popen* operation provided by the C stdio library. -- First, create the pipe instance: -- -- with Util.Streams.Pipes; -- ... -- Pipe : aliased Util.Streams.Pipes.Pipe_Stream; -- -- The pipe instance can be associated with only one process at a time. -- The process is launched by using the `Open` command and by specifying the command -- to execute as well as the pipe redirection mode: -- -- * `READ` to read the process standard output, -- * `WRITE` to write the process standard input. -- -- For example to run the `ls -l` command and read its output, we could run it by using: -- -- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ); -- -- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the -- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads -- the pipe to fill the buffer. The initialization of the buffer is the following: -- -- with Util.Streams.Buffered; -- ... -- Buffer : Util.Streams.Buffered.Input_Buffer_Stream; -- ... -- Buffer.Initialize (Input => Pipe'Access, Size => 1024); -- -- And to read the process output, one can use the following: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- ... -- Buffer.Read (Into => Content); -- -- The pipe object should be closed when reading or writing to it is finished. -- By closing the pipe, the caller will wait for the termination of the process. -- The process exit status can be obtained by using the `Get_Exit_Status` function. -- -- Pipe.Close; -- if Pipe.Get_Exit_Status /= 0 then -- Ada.Text_IO.Put_Line ("Command exited with status " -- & Integer'Image (Pipe.Get_Exit_Status)); -- end if; -- -- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied. -- When leaving the scope of the `Pipe_Stream` instance, the application will wait for -- the process to terminate. -- -- Before opening the pipe, it is possible to have some control on the process that -- will be created to configure: -- -- * The shell that will be used to launch the process, -- * The process working directory, -- * Redirect the process output to a file, -- * Redirect the process error to a file, -- * Redirect the process input from a file. -- -- All these operations must be made before calling the `Open` procedure. package Util.Streams.Pipes is use Util.Processes; subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE; -- ----------------------- -- Pipe stream -- ----------------------- -- The <b>Pipe_Stream</b> is an output/input stream that reads or writes -- to or from a process. type Pipe_Stream is limited new Output_Stream and Input_Stream with private; -- Set the shell executable path to use to launch a command. The default on Unix is -- the /bin/sh command. Argument splitting is done by the /bin/sh -c command. -- When setting an empty shell command, the argument splitting is done by the -- <tt>Spawn</tt> procedure. procedure Set_Shell (Stream : in out Pipe_Stream; Shell : in String); -- Before launching the process, redirect the input stream of the process -- to the specified file. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Input_Stream (Stream : in out Pipe_Stream; File : in String); -- Set the output stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Output_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the error stream of the process. -- Raises <b>Invalid_State</b> if the process is running. procedure Set_Error_Stream (Stream : in out Pipe_Stream; File : in String; Append : in Boolean := False); -- Set the working directory that the process will use once it is created. -- The directory must exist or the <b>Invalid_Directory</b> exception will be raised. procedure Set_Working_Directory (Stream : in out Pipe_Stream; Path : in String); -- Closes the given file descriptor in the child process before executing the command. procedure Add_Close (Stream : in out Pipe_Stream; Fd : in Util.Processes.File_Type); -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ); -- Close the pipe and wait for the external process to terminate. overriding procedure Close (Stream : in out Pipe_Stream); -- Get the process exit status. function Get_Exit_Status (Stream : in Pipe_Stream) return Integer; -- Returns True if the process is running. function Is_Running (Stream : in Pipe_Stream) return Boolean; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Terminate the process by sending a signal on Unix and exiting the process on Windows. -- This operation is not portable and has a different behavior between Unix and Windows. -- Its intent is to stop the process. procedure Stop (Stream : in out Pipe_Stream; Signal : in Positive := 15); private type Pipe_Stream is limited new Output_Stream and Input_Stream with record Proc : Util.Processes.Process; end record; end Util.Streams.Pipes;
Remove the Ada.Finalization.Limited_Controlled and Finalize Add Stop procedure to stop the process by using some signal
Remove the Ada.Finalization.Limited_Controlled and Finalize Add Stop procedure to stop the process by using some signal
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a496509e3fef5e3f2c55cdaf08266fa535912e9f
awa/src/awa-events.adb
awa/src/awa-events.adb
----------------------------------------------------------------------- -- awa-events -- AWA Events -- 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. ----------------------------------------------------------------------- package body AWA.Events is -- ------------------------------ -- Set the event type which identifies the event. -- ------------------------------ procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index) is begin Event.Kind := Kind; end Set_Event_Kind; -- ------------------------------ -- Get the event type which identifies the event. -- ------------------------------ function Get_Event_Kind (Event : in Module_Event) return Event_Index is begin return Event.Kind; end Get_Event_Kind; -- ------------------------------ -- Set a parameter on the message. -- ------------------------------ procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String) is begin Event.Props.Include (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Get the parameter with the given name. -- ------------------------------ function Get_Parameter (Event : in Module_Event; Name : in String) return String is Pos : constant Util.Beans.Objects.Maps.Cursor := Event.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then return Util.Beans.Objects.To_String (Util.Beans.Objects.Maps.Element (Pos)); else return ""; end if; end Get_Parameter; -- ------------------------------ -- Get the value that corresponds to the parameter with the given name. -- ------------------------------ function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object is begin if Event.Props.Contains (Name) then return Event.Props.Element (Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the entity identifier associated with the event. -- ------------------------------ function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier is begin return Event.Entity; end Get_Entity_Identifier; -- ------------------------------ -- Set the entity identifier associated with the event. -- ------------------------------ procedure Set_Entity_Identifier (Event : in out Module_Event; Id : in ADO.Identifier) is begin Event.Entity := Id; end Set_Entity_Identifier; -- ------------------------------ -- Copy the event properties to the map passed in <tt>Into</tt>. -- ------------------------------ procedure Copy (Event : in Module_Event; Into : in out Util.Beans.Objects.Maps.Map) is begin Into := Event.Props; end Copy; -- ------------------------------ -- Make and return a copy of the event. -- ------------------------------ function Copy (Event : in Module_Event) return Module_Event_Access is Result : constant Module_Event_Access := new Module_Event; begin Result.Kind := Event.Kind; Result.Props := Event.Props; return Result; end Copy; end AWA.Events;
----------------------------------------------------------------------- -- awa-events -- AWA Events -- Copyright (C) 2012, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; package body AWA.Events is -- ------------------------------ -- Set the event type which identifies the event. -- ------------------------------ procedure Set_Event_Kind (Event : in out Module_Event; Kind : in Event_Index) is begin Event.Kind := Kind; end Set_Event_Kind; -- ------------------------------ -- Get the event type which identifies the event. -- ------------------------------ function Get_Event_Kind (Event : in Module_Event) return Event_Index is begin return Event.Kind; end Get_Event_Kind; -- ------------------------------ -- Set a parameter on the message. -- ------------------------------ procedure Set_Parameter (Event : in out Module_Event; Name : in String; Value : in String) is begin Event.Props.Include (Name, Util.Beans.Objects.To_Object (Value)); end Set_Parameter; -- ------------------------------ -- Get the parameter with the given name. -- ------------------------------ function Get_Parameter (Event : in Module_Event; Name : in String) return String is Pos : constant Util.Beans.Objects.Maps.Cursor := Event.Props.Find (Name); begin if Util.Beans.Objects.Maps.Has_Element (Pos) then return Util.Beans.Objects.To_String (Util.Beans.Objects.Maps.Element (Pos)); else return ""; end if; end Get_Parameter; -- ------------------------------ -- Set the parameters of the message. -- ------------------------------ procedure Set_Parameters (Event : in out Module_Event; Parameters : in Util.Beans.Objects.Maps.Map) is begin Event.Props := Parameters; end Set_Parameters; -- ------------------------------ -- Get the value that corresponds to the parameter with the given name. -- ------------------------------ function Get_Value (Event : in Module_Event; Name : in String) return Util.Beans.Objects.Object is begin if Event.Props.Contains (Name) then return Event.Props.Element (Name); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the entity identifier associated with the event. -- ------------------------------ function Get_Entity_Identifier (Event : in Module_Event) return ADO.Identifier is begin return Event.Entity; end Get_Entity_Identifier; -- ------------------------------ -- Set the entity identifier associated with the event. -- ------------------------------ procedure Set_Entity_Identifier (Event : in out Module_Event; Id : in ADO.Identifier) is begin Event.Entity := Id; end Set_Entity_Identifier; -- ------------------------------ -- Set the database entity associated with the event. -- ------------------------------ procedure Set_Entity (Event : in out Module_Event; Entity : in ADO.Objects.Object_Ref'Class; Session : in ADO.Sessions.Session'Class) is Key : constant ADO.Objects.Object_Key := Entity.Get_Key; begin Event.Entity := ADO.Objects.Get_Value (Key); Event.Entity_Type := ADO.Sessions.Entities.Find_Entity_Type (Session, Key); end Set_Entity; -- ------------------------------ -- Copy the event properties to the map passed in <tt>Into</tt>. -- ------------------------------ procedure Copy (Event : in Module_Event; Into : in out Util.Beans.Objects.Maps.Map) is begin Into := Event.Props; end Copy; -- ------------------------------ -- Make and return a copy of the event. -- ------------------------------ function Copy (Event : in Module_Event) return Module_Event_Access is Result : constant Module_Event_Access := new Module_Event; begin Result.Kind := Event.Kind; Result.Props := Event.Props; return Result; end Copy; end AWA.Events;
Add Set_Entity and Set_Parameters procedures
Add Set_Entity and Set_Parameters procedures
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
dbf11c58ee7cc6cc2daddda1de06574569290373
src/asf-components-html-text.adb
src/asf-components-html-text.adb
----------------------------------------------------------------------- -- html -- ASF HTML Components -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Unchecked_Deallocation; with EL.Objects; with ASF.Components.Core; with ASF.Utils; package body ASF.Components.Html.Text is use EL.Objects; TEXT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; LABEL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Get the local value of the component without evaluating -- the associated Value_Expression. -- ------------------------------ overriding function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object is begin return UI.Value; end Get_Local_Value; -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ overriding function Get_Value (UI : in UIOutput) return EL.Objects.Object is begin if not EL.Objects.Is_Null (UI.Value) then return UI.Value; else return UI.Get_Attribute (UI.Get_Context.all, "value"); end if; end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ overriding procedure Set_Value (UI : in out UIOutput; Value : in EL.Objects.Object) is begin UI.Value := Value; end Set_Value; -- ------------------------------ -- Get the converter that is registered on the component. -- ------------------------------ overriding function Get_Converter (UI : in UIOutput) return ASF.Converters.Converter_Access is begin return UI.Converter; end Get_Converter; -- ------------------------------ -- Set the converter to be used on the component. -- ------------------------------ overriding procedure Set_Converter (UI : in out UIOutput; Converter : in ASF.Converters.Converter_Access; Release : in Boolean := False) is use type ASF.Converters.Converter_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Converter'Class, Name => ASF.Converters.Converter_Access); begin if UI.Release_Converter then Free (UI.Converter); end if; if Converter = null then UI.Converter := null; UI.Release_Converter := False; else UI.Converter := Converter.all'Unchecked_Access; UI.Release_Converter := Release; end if; end Set_Converter; -- ------------------------------ -- Get the value of the component and apply the converter on it if there is one. -- ------------------------------ function Get_Formatted_Value (UI : in UIOutput; Context : in Faces_Context'Class) return String is Value : constant EL.Objects.Object := UIOutput'Class (UI).Get_Value; begin return UIOutput'Class (UI).Get_Formatted_Value (Value, Context); end Get_Formatted_Value; -- ------------------------------ -- Get the converter associated with the component -- ------------------------------ function Get_Converter (UI : in UIOutput; Context : in Faces_Context'Class) return access ASF.Converters.Converter'Class is use type ASF.Converters.Converter_Access; Result : ASF.Converters.Converter_Access := UIOutput'Class (UI).Get_Converter; begin if Result /= null then return Result; else declare Name : constant EL.Objects.Object := UIOutput'Class (UI).Get_Attribute (Name => CONVERTER_NAME, Context => Context); begin return Context.Get_Converter (Name); end; end if; end Get_Converter; -- ------------------------------ -- Format the value by appling the To_String converter on it if there is one. -- ------------------------------ function Get_Formatted_Value (UI : in UIOutput; Value : in Util.Beans.Objects.Object; Context : in Contexts.Faces.Faces_Context'Class) return String is use type ASF.Converters.Converter_Access; begin if UI.Converter /= null then return UI.Converter.To_String (Context => Context, Component => UI, Value => Value); else declare Converter : constant access ASF.Converters.Converter'Class := UI.Get_Converter (Context); begin if Converter /= null then return Converter.To_String (Context => Context, Component => UI, Value => Value); elsif not Is_Null (Value) then return EL.Objects.To_String (Value); else return ""; end if; end; end if; -- If the converter raises an exception, report an error in the logs. -- At this stage, we know the value and we can report it in this log message. -- We must queue the exception in the context, so this is done later. exception when E : others => UI.Log_Error ("Error when converting value '{0}': {1}: {2}", Util.Beans.Objects.To_String (Value), Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); raise; end Get_Formatted_Value; procedure Write_Output (UI : in UIOutput; Context : in out Faces_Context'Class; Value : in String) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Escape : constant Object := UI.Get_Attribute (Context, "escape"); begin Writer.Start_Optional_Element ("span"); UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer); if Is_Null (Escape) or To_Boolean (Escape) then Writer.Write_Text (Value); else Writer.Write_Raw (Value); end if; Writer.End_Optional_Element ("span"); end Write_Output; procedure Encode_Begin (UI : in UIOutput; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then UI.Write_Output (Context => Context, Value => UIOutput'Class (UI).Get_Formatted_Value (Context)); end if; -- Queue any block converter exception that could be raised. exception when E : others => Context.Queue_Exception (E); end Encode_Begin; overriding procedure Finalize (UI : in out UIOutput) is begin UI.Set_Converter (null); UIHtmlComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Label Component -- ------------------------------ procedure Encode_Begin (UI : in UIOutputLabel; Context : in out Faces_Context'Class) is Writer : Response_Writer_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.Start_Element ("label"); UI.Render_Attributes (Context, LABEL_ATTRIBUTE_NAMES, Writer); declare Value : Util.Beans.Objects.Object := UI.Get_Attribute (Name => "for", Context => Context); begin if not Util.Beans.Objects.Is_Null (Value) then Writer.Write_Attribute ("for", Value); end if; Value := UIOutputLabel'Class (UI).Get_Value; if not Util.Beans.Objects.Is_Null (Value) then declare S : constant String := UIOutputLabel'Class (UI).Get_Formatted_Value (Value, Context); begin if UI.Get_Attribute (Name => "escape", Context => Context, Default => True) then Writer.Write_Text (S); else Writer.Write_Raw (S); end if; end; end if; -- Queue and block any converter exception that could be raised. exception when E : others => Context.Queue_Exception (E); end; end if; end Encode_Begin; procedure Encode_End (UI : in UIOutputLabel; Context : in out Faces_Context'Class) is Writer : Response_Writer_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.End_Element ("label"); end if; end Encode_End; -- ------------------------------ -- OutputFormat Component -- ------------------------------ procedure Encode_Begin (UI : in UIOutputFormat; Context : in out Faces_Context'Class) is use ASF.Components.Core; use ASF.Utils; begin if not UI.Is_Rendered (Context) then return; end if; declare Params : constant UIParameter_Access_Array := Get_Parameters (UI); Values : ASF.Utils.Object_Array (Params'Range); Result : Ada.Strings.Unbounded.Unbounded_String; Fmt : constant String := EL.Objects.To_String (UI.Get_Value); begin -- Get the values associated with the parameters. for I in Params'Range loop Values (I) := Params (I).Get_Value (Context); end loop; Formats.Format (Fmt, Values, Result); UI.Write_Output (Context => Context, Value => To_String (Result)); end; end Encode_Begin; begin Utils.Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES); Utils.Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES); end ASF.Components.Html.Text;
----------------------------------------------------------------------- -- html -- ASF HTML Components -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Ada.Unchecked_Deallocation; with EL.Objects; with ASF.Components.Core; with ASF.Utils; package body ASF.Components.Html.Text is use EL.Objects; TEXT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; LABEL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Get the local value of the component without evaluating -- the associated Value_Expression. -- ------------------------------ overriding function Get_Local_Value (UI : in UIOutput) return EL.Objects.Object is begin return UI.Value; end Get_Local_Value; -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ overriding function Get_Value (UI : in UIOutput) return EL.Objects.Object is begin if not EL.Objects.Is_Null (UI.Value) then return UI.Value; else return UI.Get_Attribute (UI.Get_Context.all, "value"); end if; end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ overriding procedure Set_Value (UI : in out UIOutput; Value : in EL.Objects.Object) is begin UI.Value := Value; end Set_Value; -- ------------------------------ -- Get the converter that is registered on the component. -- ------------------------------ overriding function Get_Converter (UI : in UIOutput) return ASF.Converters.Converter_Access is begin return UI.Converter; end Get_Converter; -- ------------------------------ -- Set the converter to be used on the component. -- ------------------------------ overriding procedure Set_Converter (UI : in out UIOutput; Converter : in ASF.Converters.Converter_Access; Release : in Boolean := False) is use type ASF.Converters.Converter_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Converters.Converter'Class, Name => ASF.Converters.Converter_Access); begin if UI.Release_Converter then Free (UI.Converter); end if; if Converter = null then UI.Converter := null; UI.Release_Converter := False; else UI.Converter := Converter.all'Unchecked_Access; UI.Release_Converter := Release; end if; end Set_Converter; -- ------------------------------ -- Get the value of the component and apply the converter on it if there is one. -- ------------------------------ function Get_Formatted_Value (UI : in UIOutput; Context : in Faces_Context'Class) return String is Value : constant EL.Objects.Object := UIOutput'Class (UI).Get_Value; begin return UIOutput'Class (UI).Get_Formatted_Value (Value, Context); end Get_Formatted_Value; -- ------------------------------ -- Get the converter associated with the component -- ------------------------------ function Get_Converter (UI : in UIOutput; Context : in Faces_Context'Class) return access ASF.Converters.Converter'Class is use type ASF.Converters.Converter_Access; Result : constant ASF.Converters.Converter_Access := UIOutput'Class (UI).Get_Converter; begin if Result /= null then return Result; else declare Name : constant EL.Objects.Object := UIOutput'Class (UI).Get_Attribute (Name => CONVERTER_NAME, Context => Context); begin return Context.Get_Converter (Name); end; end if; end Get_Converter; -- ------------------------------ -- Format the value by appling the To_String converter on it if there is one. -- ------------------------------ function Get_Formatted_Value (UI : in UIOutput; Value : in Util.Beans.Objects.Object; Context : in Contexts.Faces.Faces_Context'Class) return String is use type ASF.Converters.Converter_Access; begin if UI.Converter /= null then return UI.Converter.To_String (Context => Context, Component => UI, Value => Value); else declare Converter : constant access ASF.Converters.Converter'Class := UI.Get_Converter (Context); begin if Converter /= null then return Converter.To_String (Context => Context, Component => UI, Value => Value); elsif not Is_Null (Value) then return EL.Objects.To_String (Value); else return ""; end if; end; end if; -- If the converter raises an exception, report an error in the logs. -- At this stage, we know the value and we can report it in this log message. -- We must queue the exception in the context, so this is done later. exception when E : others => UI.Log_Error ("Error when converting value '{0}': {1}: {2}", Util.Beans.Objects.To_String (Value), Ada.Exceptions.Exception_Name (E), Ada.Exceptions.Exception_Message (E)); raise; end Get_Formatted_Value; procedure Write_Output (UI : in UIOutput; Context : in out Faces_Context'Class; Value : in String) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Escape : constant Object := UI.Get_Attribute (Context, "escape"); begin Writer.Start_Optional_Element ("span"); UI.Render_Attributes (Context, TEXT_ATTRIBUTE_NAMES, Writer); if Is_Null (Escape) or To_Boolean (Escape) then Writer.Write_Text (Value); else Writer.Write_Raw (Value); end if; Writer.End_Optional_Element ("span"); end Write_Output; procedure Encode_Begin (UI : in UIOutput; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then UI.Write_Output (Context => Context, Value => UIOutput'Class (UI).Get_Formatted_Value (Context)); end if; -- Queue any block converter exception that could be raised. exception when E : others => Context.Queue_Exception (E); end Encode_Begin; overriding procedure Finalize (UI : in out UIOutput) is begin UI.Set_Converter (null); UIHtmlComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Label Component -- ------------------------------ procedure Encode_Begin (UI : in UIOutputLabel; Context : in out Faces_Context'Class) is Writer : Response_Writer_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.Start_Element ("label"); UI.Render_Attributes (Context, LABEL_ATTRIBUTE_NAMES, Writer); declare Value : Util.Beans.Objects.Object := UI.Get_Attribute (Name => "for", Context => Context); begin if not Util.Beans.Objects.Is_Null (Value) then Writer.Write_Attribute ("for", Value); end if; Value := UIOutputLabel'Class (UI).Get_Value; if not Util.Beans.Objects.Is_Null (Value) then declare S : constant String := UIOutputLabel'Class (UI).Get_Formatted_Value (Value, Context); begin if UI.Get_Attribute (Name => "escape", Context => Context, Default => True) then Writer.Write_Text (S); else Writer.Write_Raw (S); end if; end; end if; -- Queue and block any converter exception that could be raised. exception when E : others => Context.Queue_Exception (E); end; end if; end Encode_Begin; procedure Encode_End (UI : in UIOutputLabel; Context : in out Faces_Context'Class) is Writer : Response_Writer_Access; begin if UI.Is_Rendered (Context) then Writer := Context.Get_Response_Writer; Writer.End_Element ("label"); end if; end Encode_End; -- ------------------------------ -- OutputFormat Component -- ------------------------------ procedure Encode_Begin (UI : in UIOutputFormat; Context : in out Faces_Context'Class) is use ASF.Components.Core; use ASF.Utils; begin if not UI.Is_Rendered (Context) then return; end if; declare Params : constant UIParameter_Access_Array := Get_Parameters (UI); Values : ASF.Utils.Object_Array (Params'Range); Result : Ada.Strings.Unbounded.Unbounded_String; Fmt : constant String := EL.Objects.To_String (UI.Get_Value); begin -- Get the values associated with the parameters. for I in Params'Range loop Values (I) := Params (I).Get_Value (Context); end loop; Formats.Format (Fmt, Values, Result); UI.Write_Output (Context => Context, Value => To_String (Result)); end; end Encode_Begin; begin Utils.Set_Text_Attributes (TEXT_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (LABEL_ATTRIBUTE_NAMES); Utils.Set_Interactive_Attributes (LABEL_ATTRIBUTE_NAMES); end ASF.Components.Html.Text;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
1658282af750d5c09cb1dc8e481bf1e1091fdfb6
src/wiki-parsers-dotclear.adb
src/wiki-parsers-dotclear.adb
----------------------------------------------------------------------- -- wiki-parsers-dotclear -- Dotclear parser operations -- Copyright (C) 2011 - 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.Nodes; with Wiki.Helpers; with Wiki.Parsers.Common; package body Wiki.Parsers.Dotclear is use Wiki.Helpers; use Wiki.Nodes; use Wiki.Strings; use Wiki.Buffers; -- Parse an image. -- Example: -- ((url|alt text)) -- ((url|alt text|position)) -- ((url|alt text|position||description)) procedure Parse_Image (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive) is Count : constant Natural := Count_Occurence (Text, From, '/'); begin if Count /= 3 then return; end if; -- Extract the format either 'Ada' or '[Ada]' declare Pos : Natural := Count + 1; Buffer : Wiki.Buffers.Buffer_Access := Text; Space_Count : Natural; begin Wiki.Strings.Clear (Parser.Preformat_Format); Buffers.Skip_Spaces (Buffer, Pos, Space_Count); if Buffer /= null and then Pos <= Buffer.Last and then Buffer.Content (Pos) = '[' then Next (Buffer, Pos); Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, ']', ']', Parser.Preformat_Format); if Buffer /= null then Next (Buffer, Pos); end if; else Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, CR, LF, Parser.Preformat_Format); end if; if Buffer /= null then Buffers.Skip_Spaces (Buffer, Pos, Space_Count); end if; Text := Buffer; From := Pos; end; Parser.Preformat_Indent := 0; Parser.Preformat_Fence := ' '; Parser.Preformat_Fcount := 0; Flush_Text (Parser, Trim => Right); Pop_Block (Parser); Push_Block (Parser, N_PREFORMAT); end Parse_Preformatted; -- ------------------------------ -- Parse an image. -- Example: -- ((url|alt text)) -- ((url|alt text|position)) -- ((url|alt text|position||description)) -- ------------------------------ procedure Parse_Image (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive) is procedure Append_Position (Position : in Wiki.Strings.WString); procedure Append_Position (Position : in Wiki.Strings.WString) is begin if Position in "L" | "G" then Wiki.Attributes.Append (Parser.Attributes, String '("align"), "left"); elsif Position in "R" | "D" then Wiki.Attributes.Append (Parser.Attributes, String '("align"), "right"); elsif Position = "C" then Wiki.Attributes.Append (Parser.Attributes, String '("align"), "center"); end if; end Append_Position; procedure Append_Position is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Position); Link : Wiki.Strings.BString (128); Alt : Wiki.Strings.BString (128); Position : Wiki.Strings.BString (128); Desc : Wiki.Strings.BString (128); Block : Wiki.Buffers.Buffer_Access := Text; Pos : Positive := From; begin Next (Block, Pos); if Block = null or else Block.Content (Pos) /= '(' then Common.Parse_Text (Parser, Text, From); return; end if; Next (Block, Pos); if Block = null then Common.Parse_Text (Parser, Text, From, Count => 2); return; end if; Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Link); if Block /= null and then Block.Content (Pos) = '|' then Next (Block, Pos); if Block /= null then Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Alt); end if; if Block /= null and then Block.Content (Pos) = '|' then Next (Block, Pos); if Block /= null then Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Position); end if; if Block /= null and then Block.Content (Pos) = '|' then Next (Block, Pos); if Block /= null then Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Desc); end if; end if; end if; end if; -- Check for the first ')'. if Block /= null and then Block.Content (Pos) = ')' then Next (Block, Pos); end if; -- Check for the second ')', abort the image and emit the '((' if the '))' is missing. if Block = null or else Block.Content (Pos) /= ')' then Common.Parse_Text (Parser, Text, From, Count => 2); return; end if; Next (Block, Pos); Text := Block; From := Pos; Flush_Text (Parser); if not Parser.Context.Is_Hidden then Wiki.Attributes.Clear (Parser.Attributes); Wiki.Attributes.Append (Parser.Attributes, "src", Link); Append_Position (Position); Wiki.Attributes.Append (Parser.Attributes, "longdesc", Desc); Parser.Context.Filters.Add_Image (Parser.Document, Strings.To_WString (Alt), Parser.Attributes); end if; end Parse_Image; procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access) is Pos : Natural := 1; C : Wiki.Strings.WChar; Count : Natural; Buffer : Wiki.Buffers.Buffer_Access := Text; begin if Parser.In_Blockquote then Count := Count_Occurence (Buffer, 1, '>'); if Count = 0 then loop Pop_Block (Parser); exit when Parser.Current_Node = Nodes.N_NONE; end loop; else Buffers.Next (Buffer, Pos, Count); Buffers.Skip_Optional_Space (Buffer, Pos); if Buffer = null then return; end if; Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count); end if; end if; if Parser.Current_Node = N_PREFORMAT then if Parser.Preformat_Fcount = 0 then Count := Count_Occurence (Buffer, 1, '/'); if Count /= 3 then Common.Append (Parser.Text, Buffer, 1); return; end if; Pop_Block (Parser); return; end if; if Buffer.Content (Pos) = ' ' then Common.Append (Parser.Text, Buffer, Pos + 1); return; end if; Pop_Block (Parser); end if; if Parser.Current_Node = N_HEADER then Pop_Block (Parser); end if; C := Buffer.Content (Pos); if C = '>' then Count := Count_Occurence (Buffer, Pos, '>'); Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count); Buffers.Next (Buffer, Pos, Count); Buffers.Skip_Optional_Space (Buffer, Pos); if Buffer = null then return; end if; C := Buffer.Content (Pos); end if; case C is when CR | LF => Common.Parse_Paragraph (Parser, Buffer, Pos); return; when '!' => Common.Parse_Header (Parser, Buffer, Pos, '!'); if Buffer = null then return; end if; when '/' => Parse_Preformatted (Parser, Buffer, Pos); if Buffer = null then return; end if; when ' ' => Parser.Preformat_Indent := 1; Parser.Preformat_Fence := ' '; Parser.Preformat_Fcount := 1; Flush_Text (Parser, Trim => Right); if Parser.Current_Node /= N_BLOCKQUOTE then Pop_Block (Parser); end if; Push_Block (Parser, N_PREFORMAT); Common.Append (Parser.Text, Buffer, Pos + 1); return; when '-' => Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-'); if Buffer = null then return; end if; when '*' | '#' => Common.Parse_List (Parser, Buffer, Pos); when others => if Parser.Current_Node not in N_PARAGRAPH | N_BLOCKQUOTE then Pop_List (Parser); Push_Block (Parser, N_PARAGRAPH); end if; end case; Main : while Buffer /= null loop declare Last : Natural := Buffer.Last; begin while Pos <= Last loop C := Buffer.Content (Pos); case C is when '_' => Parse_Format_Double (Parser, Buffer, Pos, '_', Wiki.BOLD); exit Main when Buffer = null; when ''' => Parse_Format_Double (Parser, Buffer, Pos, ''', Wiki.ITALIC); exit Main when Buffer = null; when '-' => Parse_Format_Double (Parser, Buffer, Pos, '-', Wiki.STRIKEOUT); exit Main when Buffer = null; when '+' => Parse_Format_Double (Parser, Buffer, Pos, '+', Wiki.INS); exit Main when Buffer = null; when ',' => Parse_Format_Double (Parser, Buffer, Pos, ',', Wiki.SUBSCRIPT); exit Main when Buffer = null; when '@' => Parse_Format_Double (Parser, Buffer, Pos, '@', Wiki.CODE); exit Main when Buffer = null; when '^' => Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT); exit Main when Buffer = null; when '{' => Common.Parse_Quote (Parser, Buffer, Pos, '{'); exit Main when Buffer = null; when '(' => Parse_Image (Parser, Buffer, Pos); exit Main when Buffer = null; when '[' => Common.Parse_Link (Parser, Buffer, Pos); exit Main when Buffer = null; when '<' => Common.Parse_Template (Parser, Buffer, Pos, '<'); exit Main when Buffer = null; when '%' => Count := Count_Occurence (Buffer, Pos, '%'); if Count >= 3 then Parser.Empty_Line := True; Flush_Text (Parser, Trim => Right); if not Parser.Context.Is_Hidden then Parser.Context.Filters.Add_Node (Parser.Document, Nodes.N_LINE_BREAK); end if; -- Skip 3 '%' characters. for I in 1 .. 3 loop Next (Buffer, Pos); end loop; if Buffer /= null and then Helpers.Is_Newline (Buffer.Content (Pos)) then Next (Buffer, Pos); end if; exit Main when Buffer = null; else Append (Parser.Text, C); Pos := Pos + 1; end if; when CR | LF => -- if Wiki.Strings.Length (Parser.Text) > 0 then Append (Parser.Text, ' '); -- end if; Pos := Pos + 1; when '\' => Next (Buffer, Pos); if Buffer = null then Append (Parser.Text, C); else Append (Parser.Text, Buffer.Content (Pos)); Pos := Pos + 1; Last := Buffer.Last; end if; when others => Append (Parser.Text, C); Pos := Pos + 1; end case; end loop; end; Buffer := Buffer.Next_Block; Pos := 1; end loop Main; end Parse_Line; end Wiki.Parsers.Dotclear;
----------------------------------------------------------------------- -- wiki-parsers-dotclear -- Dotclear parser operations -- Copyright (C) 2011 - 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.Nodes; with Wiki.Helpers; with Wiki.Parsers.Common; package body Wiki.Parsers.Dotclear is use Wiki.Helpers; use Wiki.Nodes; use Wiki.Strings; use Wiki.Buffers; -- Parse an image. -- Example: -- ((url|alt text)) -- ((url|alt text|position)) -- ((url|alt text|position||description)) procedure Parse_Image (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive); procedure Parse_Preformatted (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive) is Count : constant Natural := Count_Occurence (Text, From, '/'); begin if Count /= 3 then return; end if; -- Extract the format either 'Ada' or '[Ada]' declare Pos : Natural := Count + 1; Buffer : Wiki.Buffers.Buffer_Access := Text; Space_Count : Natural; begin Wiki.Strings.Clear (Parser.Preformat_Format); Buffers.Skip_Spaces (Buffer, Pos, Space_Count); if Buffer /= null and then Pos <= Buffer.Last and then Buffer.Content (Pos) = '[' then Next (Buffer, Pos); Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, ']', ']', Parser.Preformat_Format); if Buffer /= null then Next (Buffer, Pos); end if; else Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, CR, LF, Parser.Preformat_Format); end if; if Buffer /= null then Buffers.Skip_Spaces (Buffer, Pos, Space_Count); end if; Text := Buffer; From := Pos; end; Parser.Preformat_Indent := 0; Parser.Preformat_Fence := ' '; Parser.Preformat_Fcount := 0; Flush_Text (Parser, Trim => Right); Pop_Block (Parser); Push_Block (Parser, N_PREFORMAT); end Parse_Preformatted; -- ------------------------------ -- Parse an image. -- Example: -- ((url|alt text)) -- ((url|alt text|position)) -- ((url|alt text|position||description)) -- ------------------------------ procedure Parse_Image (Parser : in out Parser_Type; Text : in out Wiki.Buffers.Buffer_Access; From : in out Positive) is procedure Append_Position (Position : in Wiki.Strings.WString); procedure Append_Position (Position : in Wiki.Strings.WString) is begin if Position in "L" | "G" then Wiki.Attributes.Append (Parser.Attributes, String '("align"), "left"); elsif Position in "R" | "D" then Wiki.Attributes.Append (Parser.Attributes, String '("align"), "right"); elsif Position = "C" then Wiki.Attributes.Append (Parser.Attributes, String '("align"), "center"); end if; end Append_Position; procedure Append_Position is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Position); Link : Wiki.Strings.BString (128); Alt : Wiki.Strings.BString (128); Position : Wiki.Strings.BString (128); Desc : Wiki.Strings.BString (128); Block : Wiki.Buffers.Buffer_Access := Text; Pos : Positive := From; begin Next (Block, Pos); if Block = null or else Block.Content (Pos) /= '(' then Common.Parse_Text (Parser, Text, From); return; end if; Next (Block, Pos); if Block = null then Common.Parse_Text (Parser, Text, From, Count => 2); return; end if; Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Link); if Block /= null and then Block.Content (Pos) = '|' then Next (Block, Pos); if Block /= null then Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Alt); end if; if Block /= null and then Block.Content (Pos) = '|' then Next (Block, Pos); if Block /= null then Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Position); end if; if Block /= null and then Block.Content (Pos) = '|' then Next (Block, Pos); if Block /= null then Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Desc); end if; end if; end if; end if; -- Check for the first ')'. if Block /= null and then Block.Content (Pos) = ')' then Next (Block, Pos); end if; -- Check for the second ')', abort the image and emit the '((' if the '))' is missing. if Block = null or else Block.Content (Pos) /= ')' then Common.Parse_Text (Parser, Text, From, Count => 2); return; end if; Next (Block, Pos); Text := Block; From := Pos; Flush_Text (Parser); if not Parser.Context.Is_Hidden then Wiki.Attributes.Clear (Parser.Attributes); Wiki.Attributes.Append (Parser.Attributes, "src", Link); Append_Position (Position); Wiki.Attributes.Append (Parser.Attributes, "longdesc", Desc); Parser.Context.Filters.Add_Image (Parser.Document, Strings.To_WString (Alt), Parser.Attributes); end if; end Parse_Image; procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access) is Pos : Natural := 1; C : Wiki.Strings.WChar; Count : Natural; Buffer : Wiki.Buffers.Buffer_Access := Text; begin if Parser.In_Blockquote then Count := Count_Occurence (Buffer, 1, '>'); if Count = 0 then loop Pop_Block (Parser); exit when Parser.Current_Node = Nodes.N_NONE; end loop; else Buffers.Next (Buffer, Pos, Count); Buffers.Skip_Optional_Space (Buffer, Pos); if Buffer = null then return; end if; Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count); end if; end if; if Parser.Current_Node = N_PREFORMAT then if Parser.Preformat_Fcount = 0 then Count := Count_Occurence (Buffer, 1, '/'); if Count /= 3 then Common.Append (Parser.Text, Buffer, 1); return; end if; Pop_Block (Parser); return; end if; if Buffer.Content (Pos) = ' ' then Common.Append (Parser.Text, Buffer, Pos + 1); return; end if; Pop_Block (Parser); end if; if Parser.Current_Node = N_HEADER then Pop_Block (Parser); end if; C := Buffer.Content (Pos); if C = '>' then Count := Count_Occurence (Buffer, Pos, '>'); Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count); Buffers.Next (Buffer, Pos, Count); Buffers.Skip_Optional_Space (Buffer, Pos); if Buffer = null then return; end if; C := Buffer.Content (Pos); end if; case C is when CR | LF => Common.Parse_Paragraph (Parser, Buffer, Pos); return; when '!' => Common.Parse_Header (Parser, Buffer, Pos, '!'); if Buffer = null then return; end if; when '/' => Parse_Preformatted (Parser, Buffer, Pos); if Buffer = null then return; end if; when ' ' => Parser.Preformat_Indent := 1; Parser.Preformat_Fence := ' '; Parser.Preformat_Fcount := 1; Flush_Text (Parser, Trim => Right); if Parser.Current_Node /= N_BLOCKQUOTE then Pop_Block (Parser); end if; Push_Block (Parser, N_PREFORMAT); Common.Append (Parser.Text, Buffer, Pos + 1); return; when '-' => Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-'); if Buffer = null then return; end if; when '*' | '#' => Common.Parse_List (Parser, Buffer, Pos); when others => if Parser.Current_Node not in N_PARAGRAPH | N_BLOCKQUOTE then Pop_List (Parser); Push_Block (Parser, N_PARAGRAPH); end if; end case; Main : while Buffer /= null loop while Pos <= Buffer.Last loop C := Buffer.Content (Pos); case C is when '_' => Parse_Format_Double (Parser, Buffer, Pos, '_', Wiki.BOLD); exit Main when Buffer = null; when ''' => Parse_Format_Double (Parser, Buffer, Pos, ''', Wiki.ITALIC); exit Main when Buffer = null; when '-' => Parse_Format_Double (Parser, Buffer, Pos, '-', Wiki.STRIKEOUT); exit Main when Buffer = null; when '+' => Parse_Format_Double (Parser, Buffer, Pos, '+', Wiki.INS); exit Main when Buffer = null; when ',' => Parse_Format_Double (Parser, Buffer, Pos, ',', Wiki.SUBSCRIPT); exit Main when Buffer = null; when '@' => Parse_Format_Double (Parser, Buffer, Pos, '@', Wiki.CODE); exit Main when Buffer = null; when '^' => Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT); exit Main when Buffer = null; when '{' => Common.Parse_Quote (Parser, Buffer, Pos, '{'); exit Main when Buffer = null; when '(' => Parse_Image (Parser, Buffer, Pos); exit Main when Buffer = null; when '[' => Common.Parse_Link (Parser, Buffer, Pos); exit Main when Buffer = null; when '<' => Common.Parse_Template (Parser, Buffer, Pos, '<'); exit Main when Buffer = null; when '%' => Count := Count_Occurence (Buffer, Pos, '%'); if Count >= 3 then Parser.Empty_Line := True; Flush_Text (Parser, Trim => Right); if not Parser.Context.Is_Hidden then Parser.Context.Filters.Add_Node (Parser.Document, Nodes.N_LINE_BREAK); end if; -- Skip 3 '%' characters. for I in 1 .. 3 loop Next (Buffer, Pos); end loop; if Buffer /= null and then Helpers.Is_Newline (Buffer.Content (Pos)) then Next (Buffer, Pos); end if; exit Main when Buffer = null; else Append (Parser.Text, C); Pos := Pos + 1; end if; when CR | LF => Append (Parser.Text, ' '); Pos := Pos + 1; when '\' => Next (Buffer, Pos); if Buffer = null then Append (Parser.Text, C); else Append (Parser.Text, Buffer.Content (Pos)); Pos := Pos + 1; end if; when others => Append (Parser.Text, C); Pos := Pos + 1; end case; end loop; Buffer := Buffer.Next_Block; Pos := 1; end loop Main; end Parse_Line; end Wiki.Parsers.Dotclear;
Fix Constraint_Error raised when parsing some Dotclear documents
Fix Constraint_Error raised when parsing some Dotclear documents
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
40bfe2a66b3c7d37e27beedd9cdfb0cd7192266b
src/gen-commands-distrib.adb
src/gen-commands-distrib.adb
----------------------------------------------------------------------- -- gen-commands-distrib -- Distrib command for dynamo -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Text_IO; package body Gen.Commands.Distrib is use GNAT.Command_Line; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); begin Generator.Read_Project ("dynamo.xml", True); -- Setup the target directory where the distribution is created. declare Target_Dir : constant String := Get_Argument; begin if Target_Dir'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Target_Dir); end; -- Read the package description. declare Package_File : constant String := Get_Argument; begin if Package_File'Length > 0 then Gen.Generator.Read_Package (Generator, Package_File); else Gen.Generator.Read_Package (Generator, "package.xml"); end if; end; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("distrib: Generate the Ada files for the database model or queries"); Put_Line ("Usage: distrib target-dir [package.xml]"); New_Line; Put_Line (" Read the XML package description and build the distribution tree"); Put_Line (" and create the distribution in the target directory."); end Help; end Gen.Commands.Distrib;
----------------------------------------------------------------------- -- gen-commands-distrib -- Distrib command for dynamo -- Copyright (C) 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with Ada.Text_IO; package body Gen.Commands.Distrib is use GNAT.Command_Line; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); begin Generator.Read_Project ("dynamo.xml", True); -- Setup the target directory where the distribution is created. declare Target_Dir : constant String := Get_Argument; begin if Target_Dir'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Target_Dir); end; -- Read the package description. declare Package_File : constant String := Get_Argument; begin if Package_File'Length > 0 then Gen.Generator.Read_Package (Generator, Package_File); else Gen.Generator.Read_Package (Generator, "package.xml"); end if; end; -- Run the generation. Gen.Generator.Prepare (Generator); Gen.Generator.Generate_All (Generator); Gen.Generator.Finish (Generator); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("dist: Build the distribution files to prepare the server installation"); Put_Line ("Usage: dist target-dir [package.xml]"); New_Line; Put_Line (" The dist command reads the XML package description to build the" & " distribution tree."); Put_Line (" This command is intended to be used after the project is built. It prepares"); Put_Line (" the files for their installation on the target server in a " & "production environment."); Put_Line (" The package.xml describes what files are necessary on the server."); Put_Line (" It allows to make transformations such as compressing Javascript, CSS and " & "images"); end Help; end Gen.Commands.Distrib;
Fix the help documentation for the dist command
Fix the help documentation for the dist command
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
eeca6e22c147adcb37b801d02aa9ef70a8308107
mat/src/mat-readers-streams-files.adb
mat/src/mat-readers-streams-files.adb
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; -- Open the file. procedure Open (Reader : in out File_Reader_Type; Path : in String) is begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.File'Unchecked_Access, Output => null); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Streams.Files;
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Log.Loggers; package body MAT.Readers.Streams.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; -- ------------------------------ -- Open the file. -- ------------------------------ procedure Open (Reader : in out File_Reader_Type; Path : in String) is begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.File'Unchecked_Access, Output => null); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Streams.Files;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
2f75be2cbb2da575834e6d516b71b2020f9db209
src/ado-drivers.adb
src/ado-drivers.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- 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.Log.Loggers; with Ada.IO_Exceptions; with ADO.Queries.Loaders; package body ADO.Drivers is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); 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 Global_Config := Util.Properties.Manager (Config); -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Global_Config.Get ("ado.queries.paths", ".;db"), Global_Config.Get ("ado.queries.load", "false") = "true"); -- Initialize the drivers. ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Name : in String; Default : in String := "") return String is begin return Global_Config.Get (Name, Default); end Get_Config; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.IO_Exceptions; with ADO.Queries.Loaders; package body ADO.Drivers is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); 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 Global_Config := Util.Properties.Manager (Config); -- Configure the XML query loader. ADO.Queries.Loaders.Initialize (Global_Config.Get ("ado.queries.paths", ".;db"), Global_Config.Get ("ado.queries.load", "false") = "true"); end Initialize; -- ------------------------------ -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Name : in String; Default : in String := "") return String is begin return Global_Config.Get (Name, Default); end Get_Config; end ADO.Drivers;
Move the initialization in a separate library
Move the initialization in a separate library
Ada
apache-2.0
stcarrez/ada-ado
4ad2866cfef8f8f936ddbd3a777f4b7f85bd5bb2
src/asf-streams.ads
src/asf-streams.ads
----------------------------------------------------------------------- -- asf-streams -- Print streams for servlets -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; with Util.Streams; with Util.Streams.Texts; with EL.Objects; package ASF.Streams is -- pragma Preelaborate; -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Ada.Finalization.Limited_Controlled and Util.Streams.Output_Stream with private; procedure Initialize (Stream : in out Print_Stream; To : in Util.Streams.Texts.Print_Stream_Access); -- Initialize the stream procedure Initialize (Stream : in out Print_Stream; To : in Print_Stream'Class); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write a raw character on the stream. procedure Write (Stream : in out Print_Stream; Char : in Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write a raw string on the stream. procedure Write_Wide (Stream : in out Print_Stream; Item : in Wide_Wide_String); -- Write the object converted into a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in EL.Objects.Object); -- Write the buffer array to the output stream. procedure Write (Stream : in out Print_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. procedure Flush (Stream : in out Print_Stream); -- Write into the text stream. procedure Write (Stream : in out Print_Stream; Print : access procedure (Into : in out Util.Streams.Texts.Print_Stream'Class)); -- Close the text stream. overriding procedure Close (Stream : in out Print_Stream); private type Print_Stream is new Ada.Finalization.Limited_Controlled and Util.Streams.Output_Stream with record Target : Util.Streams.Texts.Print_Stream_Access; end record; end ASF.Streams;
----------------------------------------------------------------------- -- asf-streams -- Print streams for servlets -- 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 Ada.Streams; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Finalization; with Util.Streams; with Util.Streams.Texts; with Util.Streams.Buffered; with EL.Objects; package ASF.Streams is subtype Input_Stream is Util.Streams.Buffered.Buffered_Stream; type Input_Stream_Access is access all Input_Stream'Class; -- ----------------------- -- Print stream -- ----------------------- -- The <b>Print_Stream</b> is an output stream which provides helper methods -- for writing text streams. type Print_Stream is new Ada.Finalization.Limited_Controlled and Util.Streams.Output_Stream with private; procedure Initialize (Stream : in out Print_Stream; To : in Util.Streams.Texts.Print_Stream_Access); -- Initialize the stream procedure Initialize (Stream : in out Print_Stream; To : in Print_Stream'Class); -- Write an integer on the stream. procedure Write (Stream : in out Print_Stream; Item : in Integer); -- Write a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write a raw character on the stream. procedure Write (Stream : in out Print_Stream; Char : in Character); -- Write a raw string on the stream. procedure Write (Stream : in out Print_Stream; Item : in String); -- Write a raw string on the stream. procedure Write_Wide (Stream : in out Print_Stream; Item : in Wide_Wide_String); -- Write the object converted into a string on the stream. procedure Write (Stream : in out Print_Stream; Item : in EL.Objects.Object); -- Write the buffer array to the output stream. procedure Write (Stream : in out Print_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. procedure Flush (Stream : in out Print_Stream); -- Write into the text stream. procedure Write (Stream : in out Print_Stream; Print : access procedure (Into : in out Util.Streams.Texts.Print_Stream'Class)); -- Close the text stream. overriding procedure Close (Stream : in out Print_Stream); private type Print_Stream is new Ada.Finalization.Limited_Controlled and Util.Streams.Output_Stream with record Target : Util.Streams.Texts.Print_Stream_Access; end record; end ASF.Streams;
Declare the Input_Stream and Input_Stream_Access types
Declare the Input_Stream and Input_Stream_Access types
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
61619ece9d724a0f9ac39f9c22f9062567b7c886
src/mysql/mysql-my_list.ads
src/mysql/mysql-my_list.ads
with Interfaces.C; use Interfaces.C; with System; package Mysql.My_list is -- arg-macro: function list_rest (a) -- return (a).next; -- arg-macro: function list_push (a, b) -- return a):=list_cons((b),(a); -- Copyright (C) 2000 MySQL AB -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 2 of the License. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- /usr/include/mysql/my_list.h:24:19 type st_list is record prev : access st_list; next : access st_list; data : System.Address; end record; pragma Convention (C, st_list); subtype LIST is st_list; type List_Walk_Action is access function (arg1 : System.Address; arg2 : System.Address) return int; function list_add (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_add, "list_add"); function list_delete (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_delete, "list_delete"); function list_cons (arg1 : System.Address; arg2 : access st_list) return access st_list; pragma Import (C, list_cons, "list_cons"); function list_reverse (arg1 : access st_list) return access st_list; pragma Import (C, list_reverse, "list_reverse"); procedure list_free (arg1 : access st_list; arg2 : unsigned); pragma Import (C, list_free, "list_free"); function list_length (arg1 : access st_list) return unsigned; pragma Import (C, list_length, "list_length"); end Mysql.My_list;
with Interfaces.C; use Interfaces.C; with System; package Mysql.My_list is pragma Pure; -- arg-macro: function list_rest (a) -- return (a).next; -- arg-macro: function list_push (a, b) -- return a):=list_cons((b),(a); -- Copyright (C) 2000 MySQL AB -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 2 of the License. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- /usr/include/mysql/my_list.h:24:19 type st_list is record prev : access st_list; next : access st_list; data : System.Address; end record; pragma Convention (C, st_list); subtype LIST is st_list; type List_Walk_Action is access function (arg1 : System.Address; arg2 : System.Address) return int; function list_add (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_add, "list_add"); function list_delete (arg1 : access st_list; arg2 : access st_list) return access st_list; pragma Import (C, list_delete, "list_delete"); function list_cons (arg1 : System.Address; arg2 : access st_list) return access st_list; pragma Import (C, list_cons, "list_cons"); function list_reverse (arg1 : access st_list) return access st_list; pragma Import (C, list_reverse, "list_reverse"); procedure list_free (arg1 : access st_list; arg2 : unsigned); pragma Import (C, list_free, "list_free"); function list_length (arg1 : access st_list) return unsigned; pragma Import (C, list_length, "list_length"); end Mysql.My_list;
Make the package Pure
Make the package Pure
Ada
apache-2.0
stcarrez/ada-ado
aaa3e2d3a6fa4d80fa6d194cca6661285349b9c9
src/drivers/adabase-driver-base-postgresql.adb
src/drivers/adabase-driver-base-postgresql.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Driver.Base.PostgreSQL is ------------- -- query -- ------------- function query (driver : PostgreSQL_Driver; sql : String) return SMT.PostgreSQL_statement is begin return driver.private_statement (sql => sql, prepared => False); end query; --------------- -- prepare -- --------------- function prepare (driver : PostgreSQL_Driver; sql : String) return SMT.PostgreSQL_statement is begin return driver.private_statement (sql => sql, prepared => True); end prepare; ---------------------- -- prepare_select -- ---------------------- function prepare_select (driver : PostgreSQL_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : Null_Priority := native; limit : Trax_ID := 0; offset : Trax_ID := 0) return SMT.PostgreSQL_statement is begin return driver.private_statement (prepared => True, sql => sql_assemble (distinct => distinct, tables => tables, columns => columns, conditions => conditions, groupby => groupby, having => having, order => order, null_sort => null_sort, limit => limit, offset => offset)); end prepare_select; -------------------- -- query_select -- -------------------- function query_select (driver : PostgreSQL_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : Null_Priority := native; limit : Trax_ID := 0; offset : Trax_ID := 0) return SMT.PostgreSQL_statement is begin return driver.private_statement (prepared => False, sql => sql_assemble (distinct => distinct, tables => tables, columns => columns, conditions => conditions, groupby => groupby, having => having, order => order, null_sort => null_sort, limit => limit, offset => offset)); end query_select; -------------------- -- sql_assemble -- -------------------- function sql_assemble (distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : Null_Priority := native; limit : Trax_ID := 0; offset : Trax_ID := 0) return String is rockyroad : CT.Text; vanilla : String := assembly_common_select (distinct, tables, columns, conditions, groupby, having, order); begin rockyroad := CT.SUS (vanilla); if not CT.IsBlank (order) and then null_sort /= native then case null_sort is when native => null; when nulls_first => CT.SU.Append (rockyroad, " NULLS FIRST"); when nulls_last => CT.SU.Append (rockyroad, " NULLS LAST"); end case; end if; if limit > 0 then if offset > 0 then return CT.USS (rockyroad) & " LIMIT" & limit'Img & " OFFSET" & offset'Img; else return CT.USS (rockyroad) & " LIMIT" & limit'Img; end if; end if; return CT.USS (rockyroad); end sql_assemble; ------------------ -- initialize -- ------------------ overriding procedure initialize (Object : in out PostgreSQL_Driver) is begin Object.connection := Object.local_connection'Unchecked_Access; Object.dialect := driver_postgresql; end initialize; ----------------------- -- private_connect -- ----------------------- overriding procedure private_connect (driver : out PostgreSQL_Driver; database : String; username : String; password : String; hostname : String := blankstring; socket : String := blankstring; port : Posix_Port := portless) is err1 : constant CT.Text := CT.SUS ("ACK! Reconnection attempted on active connection"); nom : constant CT.Text := CT.SUS ("Connection to " & database & " database succeeded."); begin if driver.connection_active then driver.log_problem (category => execution, message => err1); return; end if; driver.connection.connect (database => database, username => username, password => password, socket => socket, hostname => hostname, port => port); driver.connection_active := driver.connection.connected; driver.log_nominal (category => connecting, message => nom); exception when Error : others => driver.log_problem (category => connecting, break => True, message => CT.SUS (CON.EX.Exception_Message (X => Error))); end private_connect; --------------- -- execute -- --------------- overriding function execute (driver : PostgreSQL_Driver; sql : String) return Affected_Rows is trsql : String := CT.trim_sql (sql); nquery : Natural := CT.count_queries (trsql); aborted : constant Affected_Rows := 0; err1 : constant CT.Text := CT.SUS ("ACK! Execution attempted on inactive connection"); err2 : constant String := "Driver is configured to allow only one query at " & "time, but this SQL contains multiple queries: "; begin if not driver.connection_active then -- Fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1, break => True); return aborted; end if; if nquery > 1 and then not driver.trait_multiquery_enabled then -- Fatal attempt to execute multiple queries when it's not permitted driver.log_problem (category => execution, message => CT.SUS (err2 & trsql), break => True); return aborted; end if; declare result : Affected_Rows; begin -- In order to support INSERT INTO .. RETURNING, we have to execute -- multiqueries individually because we are scanning the first 7 -- characters to be "INSERT " after converting to upper case. for query_index in Positive range 1 .. nquery loop result := 0; if nquery = 1 then driver.connection.execute (trsql); driver.log_nominal (execution, CT.SUS (trsql)); else declare SQ : constant String := CT.subquery (trsql, query_index); begin driver.connection.execute (SQ); driver.log_nominal (execution, CT.SUS (SQ)); end; end if; end loop; result := driver.connection.rows_affected_by_execution; return result; exception when CON.QUERY_FAIL => driver.log_problem (category => execution, message => CT.SUS (trsql), pull_codes => True); return aborted; end; end execute; ------------------------- -- private_statement -- ------------------------- function private_statement (driver : PostgreSQL_Driver; sql : String; prepared : Boolean) return SMT.PostgreSQL_statement is stype : AID.ASB.Stmt_Type := AID.ASB.direct_statement; logcat : Log_Category := execution; duplicate : aliased String := sql; err1 : constant CT.Text := CT.SUS ("ACK! Query attempted on inactive connection"); begin if prepared then stype := AID.ASB.prepared_statement; logcat := statement_preparation; end if; if driver.connection_active then global_statement_counter := global_statement_counter + 1; declare buffered_mode : constant Boolean := not driver.async_cmd_mode; statement : SMT.PostgreSQL_statement (type_of_statement => stype, log_handler => logger'Access, pgsql_conn => CON.PostgreSQL_Connection_Access (driver.connection), identifier => global_statement_counter, initial_sql => duplicate'Unchecked_Access, con_error_mode => driver.trait_error_mode, con_case_mode => driver.trait_column_case, con_max_blob => driver.trait_max_blob_size, con_buffered => buffered_mode); begin if not prepared then if statement.successful then driver.log_nominal (category => logcat, message => CT.SUS ("query succeeded," & statement.rows_returned'Img & " rows returned")); else driver.log_nominal (category => execution, message => CT.SUS ("Query failed!")); end if; end if; return statement; exception when RES : others => -- Fatal attempt to prepare a statement -- Logged already by stmt initialization -- Should be internally marked as unsuccessful return statement; end; else -- Fatal attempt to query an unconnected database driver.log_problem (category => logcat, message => err1, break => True); end if; -- We never get here, the driver.log_problem throws exception first raise CON.STMT_NOT_VALID with "failed to return statement"; end private_statement; -------------------------------- -- trait_query_buffers_used -- -------------------------------- function trait_query_buffers_used (driver : PostgreSQL_Driver) return Boolean is begin return not (driver.async_cmd_mode); end trait_query_buffers_used; ------------------------------ -- set_query_buffers_used -- ------------------------------ procedure set_trait_query_buffers_used (driver : PostgreSQL_Driver; trait : Boolean) is -- Once the asynchronous command mode is supported (meaning that the -- driver has to manually coordinate sending the queries and fetching -- the rows one by one), then this procedure just changes -- driver.async_cmd_mode => False. begin raise CON.UNSUPPORTED_BY_PGSQL with "Single row mode is not currently supported"; end set_trait_query_buffers_used; end AdaBase.Driver.Base.PostgreSQL;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Driver.Base.PostgreSQL is ------------- -- query -- ------------- function query (driver : PostgreSQL_Driver; sql : String) return SMT.PostgreSQL_statement is begin return driver.private_statement (sql => sql, prepared => False); end query; --------------- -- prepare -- --------------- function prepare (driver : PostgreSQL_Driver; sql : String) return SMT.PostgreSQL_statement is begin return driver.private_statement (sql => sql, prepared => True); end prepare; ---------------------- -- prepare_select -- ---------------------- function prepare_select (driver : PostgreSQL_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : Null_Priority := native; limit : Trax_ID := 0; offset : Trax_ID := 0) return SMT.PostgreSQL_statement is begin return driver.private_statement (prepared => True, sql => sql_assemble (distinct => distinct, tables => tables, columns => columns, conditions => conditions, groupby => groupby, having => having, order => order, null_sort => null_sort, limit => limit, offset => offset)); end prepare_select; -------------------- -- query_select -- -------------------- function query_select (driver : PostgreSQL_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : Null_Priority := native; limit : Trax_ID := 0; offset : Trax_ID := 0) return SMT.PostgreSQL_statement is begin return driver.private_statement (prepared => False, sql => sql_assemble (distinct => distinct, tables => tables, columns => columns, conditions => conditions, groupby => groupby, having => having, order => order, null_sort => null_sort, limit => limit, offset => offset)); end query_select; -------------------- -- sql_assemble -- -------------------- function sql_assemble (distinct : Boolean := False; tables : String; columns : String; conditions : String := blankstring; groupby : String := blankstring; having : String := blankstring; order : String := blankstring; null_sort : Null_Priority := native; limit : Trax_ID := 0; offset : Trax_ID := 0) return String is rockyroad : CT.Text; vanilla : String := assembly_common_select (distinct, tables, columns, conditions, groupby, having, order); begin rockyroad := CT.SUS (vanilla); if not CT.IsBlank (order) and then null_sort /= native then case null_sort is when native => null; when nulls_first => CT.SU.Append (rockyroad, " NULLS FIRST"); when nulls_last => CT.SU.Append (rockyroad, " NULLS LAST"); end case; end if; if limit > 0 then if offset > 0 then return CT.USS (rockyroad) & " LIMIT" & limit'Img & " OFFSET" & offset'Img; else return CT.USS (rockyroad) & " LIMIT" & limit'Img; end if; end if; return CT.USS (rockyroad); end sql_assemble; ------------------ -- initialize -- ------------------ overriding procedure initialize (Object : in out PostgreSQL_Driver) is begin Object.connection := Object.local_connection'Unchecked_Access; Object.dialect := driver_postgresql; end initialize; ----------------------- -- private_connect -- ----------------------- overriding procedure private_connect (driver : out PostgreSQL_Driver; database : String; username : String; password : String; hostname : String := blankstring; socket : String := blankstring; port : Posix_Port := portless) is err1 : constant CT.Text := CT.SUS ("ACK! Reconnection attempted on active connection"); nom : constant CT.Text := CT.SUS ("Connection to " & database & " database succeeded."); begin if driver.connection_active then driver.log_problem (category => execution, message => err1); return; end if; driver.connection.connect (database => database, username => username, password => password, socket => socket, hostname => hostname, port => port); driver.connection_active := driver.connection.connected; driver.log_nominal (category => connecting, message => nom); exception when Error : others => driver.log_problem (category => connecting, break => True, message => CT.SUS (CON.EX.Exception_Message (X => Error))); end private_connect; --------------- -- execute -- --------------- overriding function execute (driver : PostgreSQL_Driver; sql : String) return Affected_Rows is trsql : String := CT.trim_sql (sql); nquery : Natural := CT.count_queries (trsql); aborted : constant Affected_Rows := 0; err1 : constant CT.Text := CT.SUS ("ACK! Execution attempted on inactive connection"); err2 : constant String := "Driver is configured to allow only one query at " & "time, but this SQL contains multiple queries: "; begin if not driver.connection_active then -- Fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1, break => True); return aborted; end if; if nquery > 1 and then not driver.trait_multiquery_enabled then -- Fatal attempt to execute multiple queries when it's not permitted driver.log_problem (category => execution, message => CT.SUS (err2 & trsql), break => True); return aborted; end if; declare result : Affected_Rows; begin -- In order to support INSERT INTO .. RETURNING, we have to execute -- multiqueries individually because we are scanning the first 7 -- characters to be "INSERT " after converting to upper case. for query_index in Positive range 1 .. nquery loop result := 0; if nquery = 1 then driver.connection.execute (trsql); driver.log_nominal (execution, CT.SUS (trsql)); else declare SQ : constant String := CT.subquery (trsql, query_index); begin driver.connection.execute (SQ); driver.log_nominal (execution, CT.SUS (SQ)); end; end if; end loop; result := driver.connection.rows_affected_by_execution; return result; exception when CON.QUERY_FAIL => driver.log_problem (category => execution, message => CT.SUS (trsql), pull_codes => True); return aborted; end; end execute; ------------------------- -- private_statement -- ------------------------- function private_statement (driver : PostgreSQL_Driver; sql : String; prepared : Boolean) return SMT.PostgreSQL_statement is stype : AID.ASB.Stmt_Type := AID.ASB.direct_statement; logcat : Log_Category := execution; duplicate : aliased String := sql; err1 : constant CT.Text := CT.SUS ("ACK! Query attempted on inactive connection"); begin if prepared then stype := AID.ASB.prepared_statement; logcat := statement_preparation; end if; if driver.connection_active then global_statement_counter := global_statement_counter + 1; declare buffered_mode : constant Boolean := not driver.async_cmd_mode; statement : SMT.PostgreSQL_statement (type_of_statement => stype, log_handler => logger'Access, pgsql_conn => CON.PostgreSQL_Connection_Access (driver.connection), identifier => global_statement_counter, initial_sql => duplicate'Unchecked_Access, con_error_mode => driver.trait_error_mode, con_case_mode => driver.trait_column_case, con_max_blob => driver.trait_max_blob_size, con_buffered => buffered_mode); begin if not prepared then if statement.successful then driver.log_nominal (category => logcat, message => CT.SUS ("query" & global_statement_counter'Img & " succeeded," & statement.rows_returned'Img & " rows returned")); else driver.log_nominal (category => execution, message => CT.SUS ("Query" & global_statement_counter'Img & " failed!")); end if; end if; return statement; exception when RES : others => -- Fatal attempt to prepare a statement -- Logged already by stmt initialization -- Should be internally marked as unsuccessful return statement; end; else -- Fatal attempt to query an unconnected database driver.log_problem (category => logcat, message => err1, break => True); end if; -- We never get here, the driver.log_problem throws exception first raise CON.STMT_NOT_VALID with "failed to return statement"; end private_statement; -------------------------------- -- trait_query_buffers_used -- -------------------------------- function trait_query_buffers_used (driver : PostgreSQL_Driver) return Boolean is begin return not (driver.async_cmd_mode); end trait_query_buffers_used; ------------------------------ -- set_query_buffers_used -- ------------------------------ procedure set_trait_query_buffers_used (driver : PostgreSQL_Driver; trait : Boolean) is -- Once the asynchronous command mode is supported (meaning that the -- driver has to manually coordinate sending the queries and fetching -- the rows one by one), then this procedure just changes -- driver.async_cmd_mode => False. begin raise CON.UNSUPPORTED_BY_PGSQL with "Single row mode is not currently supported"; end set_trait_query_buffers_used; end AdaBase.Driver.Base.PostgreSQL;
Improve pgsql driver log messages
Improve pgsql driver log messages
Ada
isc
jrmarino/AdaBase
58868546577bd497edaa337d1d0a59c7bda8a408
src/util-events.ads
src/util-events.ads
----------------------------------------------------------------------- -- util-events -- Events -- Copyright (C) 2001, 2002, 2003, 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.Calendar; package Util.Events is type Event is tagged private; -- Get the time identifying when the event was created. function Get_Time (Ev : Event) return Ada.Calendar.Time; type Event_Listener is limited interface; private type Event is tagged record Date : Ada.Calendar.Time := Ada.Calendar.Clock; end record; end Util.Events;
----------------------------------------------------------------------- -- util-events -- Events -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; package Util.Events is type Event is tagged limited private; -- Get the time identifying when the event was created. function Get_Time (Ev : Event) return Ada.Calendar.Time; type Event_Listener is limited interface; private type Event is tagged limited record Date : Ada.Calendar.Time := Ada.Calendar.Clock; end record; end Util.Events;
Change the Event type to a limited type
Change the Event type to a limited type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
7772cabdc60dfd696dbcbd8a94300191870fc693
src/security-contexts.ads
src/security-contexts.ads
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Security.Permissions; with Security.Policies; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable -- -- * This instance will be associated with the current thread through a task attribute -- -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- -- * The result produced by the security controller is then saved in the local cache. -- package Security.Contexts is Invalid_Context : exception; Invalid_Policy : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean); -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. overriding procedure Initialize (Context : in out Security_Context); -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. overriding procedure Finalize (Context : in out Security_Context); -- Set the current application and user context. procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access); -- Set a policy context information represented by <b>Value</b> and associated with -- the <b>Policy</b>. procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access); -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access; -- Returns True if a context information was registered for the security policy. function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private -- type Permission_Cache is record -- Perm : Security.Permissions.Permission_Type; -- Result : Boolean; -- end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Policies.Policy_Manager_Access := null; Principal : Security.Principal_Access := null; Contexts : Security.Policies.Policy_Context_Array_Access := null; end record; end Security.Contexts;
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Security.Permissions; with Security.Policies; -- == Security Context == -- The security context provides contextual information for a security controller to -- verify that a permission is granted. -- This security context is used as follows: -- -- * An instance of the security context is declared within a function/procedure as -- a local variable. -- * This instance will be associated with the current thread through a task attribute -- * The security context is populated with information to identify the current user, -- his roles, permissions and other information that could be used by security controllers -- * To verify a permission, the current security context is retrieved and the -- <b>Has_Permission</b> operation is called, -- * The <b>Has_Permission</b> will first look in a small cache stored in the security context. -- * When not present in the cache, it will use the security manager to find the -- security controller associated with the permission to verify -- * The security controller will be called with the security context to check the permission. -- The whole job of checking the permission is done by the security controller. -- The security controller retrieves information from the security context to decide -- whether the permission is granted or not. -- * The result produced by the security controller is then saved in the local cache. -- -- For example the security context is declared as follows: -- -- Context : Security.Contexts.Security_Context; -- -- A security policy and a principal must be set in the security context. The security policy -- defines the rules that govern the security and the principal identifies the current user. -- -- Context.Set_Context (Policy_Manager, User); -- -- A permission is checked by using the <tt>Has_Permission</tt> operation: -- -- if Security.Contexts.Has_Permission (Perm_Create_Workspace.Permission); -- package Security.Contexts is Invalid_Context : exception; Invalid_Policy : exception; type Security_Context is new Ada.Finalization.Limited_Controlled with private; type Security_Context_Access is access all Security_Context'Class; -- Get the application associated with the current service operation. function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access; pragma Inline_Always (Get_User_Principal); -- Get the permission manager. function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean); -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. overriding procedure Initialize (Context : in out Security_Context); -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. overriding procedure Finalize (Context : in out Security_Context); -- Set the current application and user context. procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access); -- Set a policy context information represented by <b>Value</b> and associated with -- the <b>Policy</b>. procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access); -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access; -- Returns True if a context information was registered for the security policy. function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean; -- Get the current security context. -- Returns null if the current thread is not associated with any security context. function Current return Security_Context_Access; pragma Inline_Always (Current); -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean; -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. function Has_Permission (Permission : in String) return Boolean; private -- type Permission_Cache is record -- Perm : Security.Permissions.Permission_Type; -- Result : Boolean; -- end record; type Security_Context is new Ada.Finalization.Limited_Controlled with record Previous : Security_Context_Access := null; Manager : Security.Policies.Policy_Manager_Access := null; Principal : Security.Principal_Access := null; Contexts : Security.Policies.Policy_Context_Array_Access := null; end record; end Security.Contexts;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-security
a75150b657082c91d20b0f3507fc7a6523569bee
src/sys/streams/util-streams-aes.ads
src/sys/streams/util-streams-aes.ads
----------------------------------------------------------------------- -- util-streams-aes -- AES encoding and decoding streams -- 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 Util.Encoders.AES; with Util.Streams.Buffered.Encoders; -- == AES Encoding Streams == -- The `Util.Streams.AES` package define the `Encoding_Stream` and `Decoding_Stream` to -- encrypt and descrypt using the AES cipher. package Util.Streams.AES is package Encoding is new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Encoder); package Decoding is new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Decoder); type Encoding_Stream is new Encoding.Encoder_Stream with null record; -- Set the encryption key and mode to be used. procedure Set_Key (Stream : in out Encoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC); -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (Stream : in out Encoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type); type Decoding_Stream is new Decoding.Encoder_Stream with null record; -- Set the encryption key and mode to be used. procedure Set_Key (Stream : in out Decoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC); -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (Stream : in out Decoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type); end Util.Streams.AES;
----------------------------------------------------------------------- -- util-streams-aes -- AES encoding and decoding streams -- 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 Util.Encoders.AES; with Util.Streams.Buffered.Encoders; -- == AES Encoding Streams == -- The `Util.Streams.AES` package define the `Encoding_Stream` and `Decoding_Stream` types to -- encrypt and decrypt using the AES cipher. Before using these streams, you must use -- the `Set_Key` procedure to setup the encryption or decryption key and define the AES -- encryption mode to be used. The following encryption modes are supported: -- -- * AES-ECB -- * AES-CBC -- * AES-PCBC -- * AES-CFB -- * AES-OFB -- * AES-CTR -- -- The encryption and decryption keys are represented by the `Util.Encoders.Secret_Key` limited -- type. The key cannot be copied, has its content protected and will erase the memory once -- the instance is deleted. The size of the encryption key defines the AES encryption level -- to be used: -- -- * Use 16 bytes, or `Util.Encoders.AES.AES_128_Length` for AES-128, -- * Use 24 bytes, or `Util.Encoders.AES.AES_192_Length` for AES-192, -- * Use 32 bytes, or `Util.Encoders.AES.AES_256_Length` for AES-256. -- -- Other key sizes will raise a pre-condition or constraint error exception. -- The recommended key size is 32 bytes to use AES-256. The key could be declared as follows: -- -- Key : Util.Encoders.Secret_Key -- (Length => Util.Encoders.AES.AES_256_Length); -- -- The encryption and decryption key are initialized by using the `Util.Encoders.Create` -- operations or by using one of the key derivative functions provided by the -- `Util.Encoders.KDF` package. A simple string password is created by using: -- -- Password_Key : constant Util.Encoders.Secret_Key -- := Util.Encoders.Create ("mysecret"); -- -- Using a password key like this is not the good practice and it may be useful to generate -- a stronger key by using one of the key derivative function. We will use the -- PBKDF2 HMAC-SHA256 with 20000 loops (see RFC 8018): -- -- Util.Encoders.KDF.PBKDF2_HMAC_SHA256 (Password => Password_Key, -- Salt => Password_Key, -- Counter => 20000, -- Result => Key); -- -- To write a text, encrypt the content and save the file, we can chain several stream objects -- together. Because they are chained, the last stream object in the chain must be declared -- first and the first element of the chain will be declared last. The following declaration -- is used: -- -- Out_Stream : aliased Util.Streams.Files.File_Stream; -- Cipher : aliased Util.Streams.AES.Encoding_Stream; -- Printer : Util.Streams.Texts.Print_Stream; -- -- The stream objects are chained together by using their `Initialize` procedure. -- The `Out_Stream` is configured to write on the `encrypted.aes` file. -- The `Cipher` is configured to write in the `Out_Stream` with a 32Kb buffer. -- The `Printer` is configured to write in the `Cipher` with a 4Kb buffer. -- -- Out_Stream.Initialize (Mode => Ada.Streams.Stream_IO.In_File, -- Name => "encrypted.aes"); -- Cipher.Initialize (Output => Out_Stream'Access, -- Size => 32768); -- Printer.Initialize (Output => Cipher'Access, -- Size => 4096); -- -- The last step before using the cipher is to configure the encryption key and modes: -- -- Cipher.Set_Key (Secret => Key, Mode => Util.Encoders.AES.ECB); -- -- It is now possible to write the text by using the `Printer` object: -- -- Printer.Write ("Hello world!"); -- -- package Util.Streams.AES is package Encoding is new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Encoder); package Decoding is new Util.Streams.Buffered.Encoders (Encoder => Util.Encoders.AES.Decoder); type Encoding_Stream is new Encoding.Encoder_Stream with null record; -- Set the encryption key and mode to be used. procedure Set_Key (Stream : in out Encoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC); -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (Stream : in out Encoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type); type Decoding_Stream is new Decoding.Encoder_Stream with null record; -- Set the encryption key and mode to be used. procedure Set_Key (Stream : in out Decoding_Stream; Secret : in Util.Encoders.Secret_Key; Mode : in Util.Encoders.AES.AES_Mode := Util.Encoders.AES.CBC); -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (Stream : in out Decoding_Stream; IV : in Util.Encoders.AES.Word_Block_Type); end Util.Streams.AES;
Document the AES encryption and decryption streams
Document the AES encryption and decryption streams
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c4333bcfa2c3ef9af5211f32f57764326caf8423
src/wiki-strings.ads
src/wiki-strings.ads
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Wide_Wide_Maps; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Ada.Strings.Wide_Wide_Fixed; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; subtype WChar_Mapping is Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Mapping; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Substitute : in Character := ' ') return String renames Ada.Characters.Conversions.To_String; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Characters.Conversions.To_Wide_Wide_String; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; function Is_Alphanumeric (C : in WChar) return Boolean renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric; function Index (S : in WString; P : in WString; Going : in Ada.Strings.Direction := Ada.Strings.Forward; Mapping : in WChar_Mapping := Ada.Strings.Wide_Wide_Maps.Identity) return Natural renames Ada.Strings.Wide_Wide_Fixed.Index; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
----------------------------------------------------------------------- -- wiki-strings -- Wiki string types and operations -- Copyright (C) 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Wide_Wide_Maps; with Ada.Characters.Conversions; with Ada.Wide_Wide_Characters.Handling; with Ada.Strings.Wide_Wide_Fixed; with Ada.Strings.UTF_Encoding.Wide_Wide_Strings; with Util.Texts.Builders; package Wiki.Strings is pragma Preelaborate; subtype WChar is Wide_Wide_Character; subtype WString is Wide_Wide_String; subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; subtype WChar_Mapping is Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Mapping; function To_WChar (C : in Character) return WChar renames Ada.Characters.Conversions.To_Wide_Wide_Character; function To_Char (C : in WChar; Substitute : in Character := ' ') return Character renames Ada.Characters.Conversions.To_Character; function To_String (S : in WString; Output_BOM : in Boolean := False) return String renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode; function To_UString (S : in WString) return UString renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String; function To_WString (S : in UString) return WString renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String; function To_WString (S : in String) return WString renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode; procedure Append (Into : in out UString; S : in WString) renames Ada.Strings.Wide_Wide_Unbounded.Append; procedure Append (Into : in out UString; S : in WChar) renames Ada.Strings.Wide_Wide_Unbounded.Append; function Length (S : in UString) return Natural renames Ada.Strings.Wide_Wide_Unbounded.Length; function Element (S : in UString; Pos : in Positive) return WChar renames Ada.Strings.Wide_Wide_Unbounded.Element; function Is_Alphanumeric (C : in WChar) return Boolean renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric; function Index (S : in WString; P : in WString; Going : in Ada.Strings.Direction := Ada.Strings.Forward; Mapping : in WChar_Mapping := Ada.Strings.Wide_Wide_Maps.Identity) return Natural renames Ada.Strings.Wide_Wide_Fixed.Index; Null_UString : UString renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String; package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar, Input => WString, Chunk_Size => 512); subtype BString is Wide_Wide_Builders.Builder; end Wiki.Strings;
Use Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode/Decode for the String to Wide_Wide_String conversion so that UTF-8 is translated correctly
Use Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode/Decode for the String to Wide_Wide_String conversion so that UTF-8 is translated correctly
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
c7df43420597187c69c7e87f26528842ced00d1c
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, 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;
----------------------------------------------------------------------- -- 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; type Member_List_Bean_Access is access all Member_List_Bean'Class; -- Load the list of members. overriding procedure Load (Into : in out Member_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Member_List_Bean bean instance. function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Workspaces.Beans;
Declare the Create_Member_List_Bean function
Declare the Create_Member_List_Bean function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2305472b91032cc4213af277690e7bab08e5e37d
src/unix.adb
src/unix.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with GNAT.OS_Lib; with Ada.Text_IO; with Parameters; with System; package body Unix is package OSL renames GNAT.OS_Lib; package TIO renames Ada.Text_IO; package PM renames Parameters; ---------------------- -- process_status -- ---------------------- function process_status (pid : pid_t) return process_exit is result : constant uInt8 := nohang_waitpid (pid); begin case result is when 0 => return still_running; when 1 => return exited_normally; when others => return exited_with_error; end case; end process_status; ----------------------- -- cone_of_silence -- ----------------------- procedure cone_of_silence (deploy : Boolean) is result : uInt8; begin if CSM.isatty (handle => CSM.fileno (CSM.stdin)) = 0 then return; end if; if deploy then result := silent_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control OFF command failed"); end if; else result := chatty_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control ON command failed"); end if; end if; end cone_of_silence; ------------------------- -- kill_process_tree -- ------------------------- procedure kill_process_tree (process_group : pid_t) is pgid : constant String := process_group'Img; dfly_cmd : constant String := "/usr/bin/pkill -KILL -g"; free_cmd : constant String := "/bin/pkill -KILL -g"; killres : Boolean; begin if JT.equivalent (PM.configuration.operating_sys, "FreeBSD") then killres := external_command (free_cmd & pgid); else killres := external_command (dfly_cmd & pgid); end if; end kill_process_tree; ------------------------ -- external_command -- ------------------------ function external_command (command : String) return Boolean is Args : OSL.Argument_List_Access; Exit_Status : Integer; begin Args := OSL.Argument_String_To_List (command); Exit_Status := OSL.Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return Exit_Status = 0; end external_command; ------------------- -- fork_failed -- ------------------- function fork_failed (pid : pid_t) return Boolean is begin if pid < 0 then return True; end if; return False; end fork_failed; ---------------------- -- launch_process -- ---------------------- function launch_process (command : String) return pid_t is procid : OSL.Process_Id; Args : OSL.Argument_List_Access; begin Args := OSL.Argument_String_To_List (command); procid := OSL.Non_Blocking_Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return pid_t (OSL.Pid_To_Integer (procid)); end launch_process; ---------------------------- -- env_variable_defined -- ---------------------------- function env_variable_defined (variable : String) return Boolean is test : String := OSL.Getenv (variable).all; begin return (test /= ""); end env_variable_defined; -------------------------- -- env_variable_value -- -------------------------- function env_variable_value (variable : String) return String is begin return OSL.Getenv (variable).all; end env_variable_value; ------------------ -- pipe_close -- ------------------ function pipe_close (OpenFile : CSM.FILEs) return Integer is res : constant CSM.int := pclose (FileStream => OpenFile); u16 : Interfaces.Unsigned_16; begin u16 := Interfaces.Shift_Right (Interfaces.Unsigned_16 (res), 8); return Integer (u16); end pipe_close; --------------------- -- piped_command -- --------------------- function piped_command (command : String; status : out Integer) return JT.Text is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; result : JT.Text; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("r")); result := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); return result; end piped_command; -------------------------- -- piped_mute_command -- -------------------------- function piped_mute_command (command : String) return Boolean is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; status : Integer; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("r")); status := pipe_close (OpenFile => filestream); return status = 0; end piped_mute_command; ----------------- -- pipe_read -- ----------------- function pipe_read (OpenFile : CSM.FILEs) return JT.Text is -- Allocate 2kb at a time buffer : String (1 .. 2048) := (others => ' '); result : JT.Text := JT.blank; charbuf : CSM.int; marker : Natural := 0; begin loop charbuf := CSM.fgetc (OpenFile); if charbuf = CSM.EOF then if marker >= buffer'First then JT.SU.Append (result, buffer (buffer'First .. marker)); end if; exit; end if; if marker = buffer'Last then JT.SU.Append (result, buffer); marker := buffer'First; else marker := marker + 1; end if; buffer (marker) := Character'Val (charbuf); end loop; return result; end pipe_read; end Unix;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with GNAT.OS_Lib; with Ada.Text_IO; with Parameters; with System; package body Unix is package OSL renames GNAT.OS_Lib; package TIO renames Ada.Text_IO; package PM renames Parameters; ---------------------- -- process_status -- ---------------------- function process_status (pid : pid_t) return process_exit is result : constant uInt8 := nohang_waitpid (pid); begin case result is when 0 => return still_running; when 1 => return exited_normally; when others => return exited_with_error; end case; end process_status; ----------------------- -- cone_of_silence -- ----------------------- procedure cone_of_silence (deploy : Boolean) is result : uInt8; begin if CSM.isatty (handle => CSM.fileno (CSM.stdin)) = 0 then return; end if; if deploy then result := silent_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control OFF command failed"); end if; else result := chatty_control; if result > 0 then TIO.Put_Line ("Notice: tty echo+control ON command failed"); end if; end if; end cone_of_silence; ------------------------- -- kill_process_tree -- ------------------------- procedure kill_process_tree (process_group : pid_t) is pgid : constant String := process_group'Img; dfly_cmd : constant String := "/usr/bin/pkill -KILL -g"; free_cmd : constant String := "/bin/pkill -KILL -g"; killres : Boolean; begin if JT.equivalent (PM.configuration.operating_sys, "FreeBSD") then killres := external_command (free_cmd & pgid); else killres := external_command (dfly_cmd & pgid); end if; end kill_process_tree; ------------------------ -- external_command -- ------------------------ function external_command (command : String) return Boolean is Args : OSL.Argument_List_Access; Exit_Status : Integer; begin Args := OSL.Argument_String_To_List (command); Exit_Status := OSL.Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return Exit_Status = 0; end external_command; ------------------- -- fork_failed -- ------------------- function fork_failed (pid : pid_t) return Boolean is begin if pid < 0 then return True; end if; return False; end fork_failed; ---------------------- -- launch_process -- ---------------------- function launch_process (command : String) return pid_t is procid : OSL.Process_Id; Args : OSL.Argument_List_Access; begin Args := OSL.Argument_String_To_List (command); procid := OSL.Non_Blocking_Spawn (Program_Name => Args (Args'First).all, Args => Args (Args'First + 1 .. Args'Last)); OSL.Free (Args); return pid_t (OSL.Pid_To_Integer (procid)); end launch_process; ---------------------------- -- env_variable_defined -- ---------------------------- function env_variable_defined (variable : String) return Boolean is test : String := OSL.Getenv (variable).all; begin return (test /= ""); end env_variable_defined; -------------------------- -- env_variable_value -- -------------------------- function env_variable_value (variable : String) return String is begin return OSL.Getenv (variable).all; end env_variable_value; ------------------ -- pipe_close -- ------------------ function pipe_close (OpenFile : CSM.FILEs) return Integer is res : constant CSM.int := pclose (FileStream => OpenFile); u16 : Interfaces.Unsigned_16; begin u16 := Interfaces.Shift_Right (Interfaces.Unsigned_16 (res), 8); if Integer (u16) > 0 then return Integer (u16); end if; return Integer (res); end pipe_close; --------------------- -- piped_command -- --------------------- function piped_command (command : String; status : out Integer) return JT.Text is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; result : JT.Text; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("r")); result := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); return result; end piped_command; -------------------------- -- piped_mute_command -- -------------------------- function piped_mute_command (command : String) return Boolean is redirect : constant String := " 2>&1"; filestream : CSM.FILEs; status : Integer; result : JT.Text; begin filestream := popen (IC.To_C (command & redirect), IC.To_C ("r")); result := pipe_read (OpenFile => filestream); status := pipe_close (OpenFile => filestream); if status /= 0 then TIO.Put_Line ("piped_mute_command failure:"); TIO.Put_Line (" => " & JT.USS (result)); end if; return status = 0; end piped_mute_command; ----------------- -- pipe_read -- ----------------- function pipe_read (OpenFile : CSM.FILEs) return JT.Text is -- Allocate 2kb at a time buffer : String (1 .. 2048) := (others => ' '); result : JT.Text := JT.blank; charbuf : CSM.int; marker : Natural := 0; begin loop charbuf := CSM.fgetc (OpenFile); if charbuf = CSM.EOF then if marker >= buffer'First then JT.SU.Append (result, buffer (buffer'First .. marker)); end if; exit; end if; if marker = buffer'Last then JT.SU.Append (result, buffer); marker := buffer'First; else marker := marker + 1; end if; buffer (marker) := Character'Val (charbuf); end loop; return result; end pipe_read; end Unix;
Fix piped command exit statuses (issue #33)
Fix piped command exit statuses (issue #33) There were two inter-related problems. The first one appears that if the pipe isn't read, the pclose return status isn't accurate. I discovered this accidently with a heisenbug. As soon as I read the pipe to output the message, the exit status changed to "good". The second bug was the exit status was not being returned correctly. Now if the process exits abnormally, you get that exit status, and if it exits normally but with a non-zero value (the child status), then that is returned. As a new feature, if a muted piped command does result in an unexpected non-zero status, synth will output the result of the command (which contains the error message) and that will be followed by an unhandled exception that contains the command text. This would havd revealed the problem with mtree in issue #33.
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
b484527807c9c2acc4ab538c8b254fa92c8455c8
awa/regtests/awa-commands-tests.ads
awa/regtests/awa-commands-tests.ads
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test start and stop command. procedure Test_Start_Stop (T : in out Test); procedure Test_List_Tables (T : in out Test); procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); end AWA.Commands.Tests;
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Ada.Strings.Unbounded; package AWA.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test start and stop command. procedure Test_Start_Stop (T : in out Test); procedure Test_List_Tables (T : in out Test); -- Test the list -u command. procedure Test_List_Users (T : in out Test); -- Test the list -s command. procedure Test_List_Sessions (T : in out Test); -- Test the list -j command. procedure Test_List_Jobs (T : in out Test); procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); end AWA.Commands.Tests;
Declare Test_List_Users, Test_List_Sessions, Test_List_Jobs procedures
Declare Test_List_Users, Test_List_Sessions, Test_List_Jobs procedures
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
45e8fc5a5b659fc53ba8acbf5571a33665dd4d6f
regtests/util-commands-tests.adb
regtests/util-commands-tests.adb
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- 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.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration); -- Write the help associated with the command. procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration) is begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type) is begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); D.Usage (Args); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- 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.Command_Line; with Util.Test_Caller; with Util.Commands.Parsers.GNAT_Parser; with Util.Commands.Drivers; package body Util.Commands.Tests is package Caller is new Util.Test_Caller (Test, "Commands"); type Test_Context_Type is record Number : Integer; Success : Boolean := False; end record; package Test_Command is new Util.Commands.Drivers (Context_Type => Test_Context_Type, Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser, Driver_Name => "test"); type Test_Command_Type is new Test_Command.Command_Type with record Opt_Count : aliased Integer := 0; Opt_V : aliased Boolean := False; Opt_N : aliased Boolean := False; Expect_V : Boolean := False; Expect_N : Boolean := False; Expect_C : Integer := 0; Expect_A : Integer := 0; Expect_Help : Boolean := False; end record; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type); -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration); -- Write the help associated with the command. procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute", Test_Execute'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help", Test_Help'Access); Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage", Test_Usage'Access); end Add_Tests; overriding procedure Execute (Command : in out Test_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Test_Context_Type) is pragma Unreferenced (Name); begin Context.Success := Command.Opt_Count = Command.Expect_C and Command.Opt_V = Command.Expect_V and Command.Opt_N = Command.Expect_N and Args.Get_Count = Command.Expect_A and not Command.Expect_Help; end Execute; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup (Command : in out Test_Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration) is begin GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-c:", Long_Switch => "--count=", Help => "Number option", Section => "", Initial => Integer (0), Default => Integer (10), Output => Command.Opt_Count'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-v", Long_Switch => "--verbose", Help => "Verbose option", Section => "", Output => Command.Opt_V'Access); GNAT.Command_Line.Define_Switch (Config => Config, Switch => "-n", Long_Switch => "--not", Help => "Not option", Section => "", Output => Command.Opt_N'Access); end Setup; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in Test_Command_Type; Context : in out Test_Context_Type) is begin Context.Success := Command.Expect_Help; end Help; -- ------------------------------ -- Tests when the execution of commands. -- ------------------------------ procedure Test_Execute (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_V := True; C1.Expect_N := True; C1.Expect_C := 4; C1.Expect_A := 2; Initialize (Args, "list --count=4 -v -n test titi"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C1.Expect_V := False; C1.Expect_N := True; C1.Expect_C := 8; C1.Expect_A := 3; Initialize (Args, "list -c 8 -n test titi last"); D.Execute ("list", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Execute; -- ------------------------------ -- Test execution of help. -- ------------------------------ procedure Test_Help (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; declare Ctx : Test_Context_Type; begin C2.Expect_Help := True; Initialize (Args, "help print"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Help; -- ------------------------------ -- Test usage operation. -- ------------------------------ procedure Test_Usage (T : in out Test) is C1 : aliased Test_Command_Type; C2 : aliased Test_Command_Type; H : aliased Test_Command.Help_Command_Type; D : Test_Command.Driver_Type; Args : String_Argument_List (500, 30); begin D.Set_Description ("Test command"); D.Add_Command ("list", C1'Unchecked_Access); D.Add_Command ("print", C2'Unchecked_Access); D.Add_Command ("help", H'Unchecked_Access); Args.Initialize (Line => "cmd list"); D.Usage (Args); declare Ctx : Test_Context_Type; begin C1.Expect_Help := True; Initialize (Args, "help list"); D.Execute ("help", Args, Ctx); T.Assert (Ctx.Success, "Some arguments not parsed correctly"); end; end Test_Usage; end Util.Commands.Tests;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
ca29d4be7fdad4401d415801b1ecf2905fe1eabd
awa/plugins/awa-jobs/src/awa-jobs.ads
awa/plugins/awa-jobs/src/awa-jobs.ads
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 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. ----------------------------------------------------------------------- -- = Jobs Module = -- The `AWA.Jobs` plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. The `Jobs` plugin is intended to help web application -- designers in implementing end to end asynchronous operation. A client schedules a job -- and does not block nor wait for the immediate completion. Instead, the client asks -- periodically or uses other mechanisms to check for the job completion. -- -- == Writing a job == -- A new job type is created by implementing the `Execute` operation of the abstract -- `Job_Type` tagged record. -- -- type Resize_Job is new AWA.Jobs.Job_Type with ...; -- -- The `Execute` procedure must be implemented. It should use the `Get_Parameter` functions -- to retrieve the job parameters and perform the work. While the job is being executed, -- it can save result by using the `Set_Result` operations, save messages by using the -- `Set_Message` operations and report the progress by using `Set_Progress`. -- It may report the job status by using `Set_Status`. -- -- procedure Execute (Job : in out Resize_Job) is -- begin -- Job.Set_Result ("done", "ok"); -- end Execute; -- -- == Registering a job == -- The `AWA.Jobs` plugin must be able to create the job instance when it is going to -- be executed. For this, a registration package must be instantiated: -- -- package Resize_Def is new AWA.Jobs.Definition (Resize_Job); -- -- and the job definition must be added: -- -- AWA.Jobs.Modules.Register (Resize_Def.Create'Access); -- -- == Scheduling a job == -- To schedule a job, declare an instance of the job to execute and set the job specific -- parameters. The job parameters will be saved in the database. As soon as parameters -- are defined, call the `Schedule` procedure to schedule the job in the job queue and -- obtain a job identifier. -- -- Resize : Resize_Job; -- ... -- Resize.Set_Parameter ("file", "image.png"); -- Resize.Set_Parameter ("width", "32"); -- Resize.Set_Parameter ("height, "32"); -- Resize.Schedule; -- -- == Checking for job completion == -- -- -- @include awa-jobs-modules.ads -- @include awa-jobs-services.ads -- -- @include jobs.xml -- -- == Data Model == -- [images/awa_jobs_model.png] -- package AWA.Jobs is end AWA.Jobs;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012, 2015, 2018, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- = Jobs Module = -- The `AWA.Jobs` plugin defines a batch job framework for modules to perform and execute -- long running and deferred actions. The `Jobs` plugin is intended to help web application -- designers in implementing end to end asynchronous operation. A client schedules a job -- and does not block nor wait for the immediate completion. Instead, the client asks -- periodically or uses other mechanisms to check for the job completion. -- -- == Writing a job == -- A new job type is created by implementing the `Execute` operation of the abstract -- `Job_Type` tagged record. -- -- type Resize_Job is new AWA.Jobs.Job_Type with ...; -- -- The `Execute` procedure must be implemented. It should use the `Get_Parameter` functions -- to retrieve the job parameters and perform the work. While the job is being executed, -- it can save result by using the `Set_Result` operations, save messages by using the -- `Set_Message` operations and report the progress by using `Set_Progress`. -- It may report the job status by using `Set_Status`. -- -- procedure Execute (Job : in out Resize_Job) is -- begin -- Job.Set_Result ("done", "ok"); -- end Execute; -- -- == Registering a job == -- The `AWA.Jobs` plugin must be able to create the job instance when it is going to -- be executed. For this, a registration package must be instantiated: -- -- package Resize_Def is new AWA.Jobs.Definition (Resize_Job); -- -- and the job definition must be added: -- -- AWA.Jobs.Modules.Register (Resize_Def.Create'Access); -- -- == Scheduling a job == -- To schedule a job, declare an instance of the job to execute and set the job specific -- parameters. The job parameters will be saved in the database. As soon as parameters -- are defined, call the `Schedule` procedure to schedule the job in the job queue and -- obtain a job identifier. -- -- Resize : Resize_Job; -- ... -- Resize.Set_Parameter ("file", "image.png"); -- Resize.Set_Parameter ("width", "32"); -- Resize.Set_Parameter ("height, "32"); -- Resize.Schedule; -- -- == Checking for job completion == -- After a job is scheduled, a unique identifier is allocated that allows to identify it. -- It is possible to query the status of the job by using the `Get_Job_Status` -- function: -- -- Status : AWA.Jobs.Models.Job_Status_Type -- := AWA.Jobs.Services.Get_Job_Status (Resize.Get_Identifier); -- -- @include awa-jobs-modules.ads -- @include awa-jobs-services.ads -- -- @include jobs.xml -- -- == Data Model == -- [images/awa_jobs_model.png] -- package AWA.Jobs is end AWA.Jobs;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5d95aec95e58b9a4854991740d5f73ee616b8bee
src/core/texts/util-texts-builders.ads
src/core/texts/util-texts-builders.ads
----------------------------------------------------------------------- -- util-texts-builders -- Text builder -- Copyright (C) 2013, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Ada.Finalization; -- == Text Builders == -- The `Util.Texts.Builders` generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The `Builder` 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 `Append` procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the `Iterate` operation that allows to get the content -- collected by the builder. When using the `Iterate` operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- 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 receives -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the `Iterate` 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); generic with procedure Process (Content : in out Input; Last : out Natural); procedure Inline_Append (Source : in out Builder); -- 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)); generic with procedure Process (Content : in Input); procedure Inline_Iterate (Source : in Builder); -- 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; -- Get the element at the given position. function Element (Source : in Builder; Position : in Positive) return Element_Type; -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. generic with function Index (Content : in Input) return Natural; function Find (Source : in Builder; Position : in Positive) return Natural; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Input); procedure Get (Source : in Builder); -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream generic type Value is limited private; type Value_List is array (Positive range <>) of Value; with procedure Append (Input : in out Builder; Item : in Value); procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List); 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, 2017, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Ada.Finalization; -- == Text Builders == -- The `Util.Texts.Builders` generic package was designed to provide string builders. -- The interface was designed to reduce memory copies as much as possible. -- -- * The `Builder` 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 `Append` procedure which allows to append text to the builder. -- This is the only time when a copy is made. -- * The package defines the `Iterate` operation that allows to get the content -- collected by the builder. When using the `Iterate` operation, no copy is -- performed since chunks data are passed passed by reference. -- * The type is limited to forbid copies of the builder instance. -- -- 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 receives -- the chunk data as parameter: -- -- procedure Collect (Item : in String) is ... -- -- And use the `Iterate` 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); -- Append in `Into` builder the `Content` builder starting at `From` position -- and the up to and including the `To` position. procedure Append (Into : in out Builder; Content : in Builder; From : in Positive; To : in Positive); generic with procedure Process (Content : in out Input; Last : out Natural); procedure Inline_Append (Source : in out Builder); -- 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)); generic with procedure Process (Content : in Input); procedure Inline_Iterate (Source : in Builder); -- 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; -- Get the element at the given position. function Element (Source : in Builder; Position : in Positive) return Element_Type; -- Find the position of some content by running the `Index` function. -- The `Index` function is called with chunks starting at the given position and -- until it returns a positive value or we reach the last chunk. It must return -- the found position in the chunk. generic with function Index (Content : in Input) return Natural; function Find (Source : in Builder; Position : in Positive) return Natural; -- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid -- secondary stack copies as much as possible. generic with procedure Process (Content : in Input); procedure Get (Source : in Builder); -- Format the message and replace occurrences of argument patterns by -- their associated value. -- Returns the formatted message in the stream generic type Value is limited private; type Value_List is array (Positive range <>) of Value; with procedure Append (Input : in out Builder; Item : in Value); procedure Format (Into : in out Builder; Message : in Input; Arguments : in Value_List); 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 Append procedure to append the content of a builder in another
Declare the Append procedure to append the content of a builder in another
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
888be85e87821f0102297fb5074b5446d50c4ac4
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "0"; synth_version_minor : constant String := "90"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "0"; synth_version_minor : constant String := "95"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Bump version to 0.95, it's pretty usable now. Time for testing!
Bump version to 0.95, it's pretty usable now. Time for testing!
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
b344d017540efc2e51dfb6497b324f92a578c8c5
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.adb
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for storage service -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Votes.Modules; with AWA.Tests.Helpers.Users; package body AWA.Votes.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Votes.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For", Test_Vote_Up'Access); Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For (Undo)", Test_Vote_Undo'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Vote_Up (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : Vote_Module_Access := Get_Vote_Module; User : AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total); end; end Test_Vote_Up; -- ------------------------------ -- Test vote. -- ------------------------------ procedure Test_Vote_Undo (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : Vote_Module_Access := Get_Vote_Module; User : AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 0, Total); end; end Test_Vote_Undo; end AWA.Votes.Modules.Tests;
----------------------------------------------------------------------- -- 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 Util.Test_Caller; with Security.Contexts; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Votes.Modules; with AWA.Tests.Helpers.Users; package body AWA.Votes.Modules.Tests is use Util.Tests; use ADO; package Caller is new Util.Test_Caller (Test, "Votes.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For", Test_Vote_Up'Access); Caller.Add_Test (Suite, "Test AWA.Votes.Modules.Vote_For (Undo)", Test_Vote_Undo'Access); end Add_Tests; -- ------------------------------ -- Test creation of a question. -- ------------------------------ procedure Test_Vote_Up (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : constant Vote_Module_Access := Get_Vote_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total); T.Assert (Total > 0, "Invalid total"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total); T.Assert (Total > 0, "Invalid total"); end; end Test_Vote_Up; -- ------------------------------ -- Test vote. -- ------------------------------ procedure Test_Vote_Undo (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); declare Vote_Manager : constant Vote_Module_Access := Get_Vote_Module; User : constant AWA.Users.Models.User_Ref := Context.Get_User; Total : Integer; begin T.Assert (Vote_Manager /= null, "There is no vote module"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 1, Total); T.Assert (Total > 0, "Invalid total"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 2, Total); T.Assert (Total > 0, "Invalid total"); Vote_Manager.Vote_For (User.Get_Id, "awa_user", "workspaces-create", 0, Total); T.Assert (Total >= 0, "Invalid total"); end; end Test_Vote_Undo; end AWA.Votes.Modules.Tests;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
926364568a81d03a08a83fdf83d1e442e657c176
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.ads
awa/plugins/awa-votes/regtests/awa-votes-modules-tests.ads
----------------------------------------------------------------------- -- awa-votes-modules-tests -- Unit tests for vote 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 Util.Tests; with AWA.Tests; package AWA.Votes.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Votes.Modules.Vote_Module_Access; end record; -- Test vote. procedure Test_Vote_Up (T : in out Test); end AWA.Votes.Modules.Tests;
----------------------------------------------------------------------- -- awa-votes-modules-tests -- Unit tests for vote 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 Util.Tests; with AWA.Tests; package AWA.Votes.Modules.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Votes.Modules.Vote_Module_Access; end record; -- Test vote. procedure Test_Vote_Up (T : in out Test); -- Test vote. procedure Test_Vote_Undo (T : in out Test); end AWA.Votes.Modules.Tests;
Add unit test for undo vote
Add unit test for undo vote
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
c7b93757737080b292220a62eb13a2760ee336f4
src/gen-artifacts-query.adb
src/gen-artifacts-query.adb
----------------------------------------------------------------------- -- gen-artifacts-query -- Query artifact for Code Generator -- 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.Strings.Unbounded; with Ada.Directories; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Util.Log.Loggers; with Util.Encoders.HMAC.SHA1; -- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of -- data structures returned by queries. package body Gen.Artifacts.Query is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Model.Queries; use Gen.Configs; use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query"); -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node); procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node); procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); Hash : Unbounded_String; -- ------------------------------ -- Register the column definition in the table -- ------------------------------ procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name"); C : Column_Definition_Access; begin Table.Add_Column (Name, C); C.Initialize (Name, Column); C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type")); C.Is_Inserted := False; C.Is_Updated := False; C.Not_Null := False; C.Unique := False; -- Construct the hash for this column mapping. Append (Hash, ",type="); Append (Hash, C.Type_Name); Append (Hash, ",name="); Append (Hash, Name); end Register_Column; -- ------------------------------ -- Register all the columns defined in the table -- ------------------------------ procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Column); begin Log.Debug ("Register columns from query {0}", Table.Name); Iterate (Table, Node, "property"); end Register_Columns; -- ------------------------------ -- Register the sort definition in the query -- ------------------------------ procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Sql : constant String := Gen.Utils.Get_Data_Content (Node); begin Query.Add_Sort (Name, To_Unbounded_String (Sql)); end Register_Sort; -- ------------------------------ -- Register all the sort modes defined in the query -- ------------------------------ procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Sort); begin Log.Debug ("Register sorts from query {0}", Query.Name); Iterate (Query, Node, "order"); end Register_Sorts; -- ------------------------------ -- Register a new class definition in the model. -- ------------------------------ procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); begin Query.Initialize (Name, Node); Query.Set_Table_Name (To_String (Name)); if Name /= "" then Query.Name := Name; else Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path)); end if; -- Construct the hash for this column mapping. Append (Hash, "class="); Append (Hash, Query.Name); Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name); Register_Columns (Query_Definition (Query), Node); end Register_Mapping; -- ------------------------------ -- Register a new query. -- ------------------------------ procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); C : Gen.Model.Queries.Query_Definition_Access; begin Query.Add_Query (Name, C); Register_Sorts (Query_Definition (C.all), Node); end Register_Query; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node) is procedure Iterate_Mapping is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Mapping); procedure Iterate_Query is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Query); Table : constant Query_File_Definition_Access := new Query_File_Definition; Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package"); Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table"); begin Table.Initialize (Name, Node); Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path)); Table.Pkg_Name := Pkg; Iterate_Mapping (Query_File_Definition (Table.all), Node, "class"); Iterate_Query (Query_File_Definition (Table.all), Node, "query"); if Length (Table.Pkg_Name) = 0 then Context.Error ("Missing or empty package attribute"); else Model.Register_Query (Table); end if; Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash)); Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries", Data => To_String (Hash)); end Register_Mapping; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition, Process => Register_Mapping); begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); begin Log.Debug ("Preparing the model for query"); if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; end Gen.Artifacts.Query;
----------------------------------------------------------------------- -- gen-artifacts-query -- Query artifact for Code Generator -- 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.Strings.Unbounded; with Ada.Directories; with Gen.Configs; with Gen.Utils; with Gen.Model.Tables; with Gen.Model.Queries; with Gen.Model.Mappings; with Gen.Model.Operations; with Util.Log.Loggers; with Util.Encoders.HMAC.SHA1; -- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of -- data structures returned by queries. package body Gen.Artifacts.Query is use Ada.Strings.Unbounded; use Gen.Model; use Gen.Model.Tables; use Gen.Model.Queries; use Gen.Configs; use type DOM.Core.Node; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query"); -- ------------------------------ -- After the configuration file is read, processes the node whose root -- is passed in <b>Node</b> and initializes the <b>Model</b> with the information. -- ------------------------------ procedure Initialize (Handler : in out Artifact; Path : in String; Node : in DOM.Core.Node; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node); procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node); procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node); Hash : Unbounded_String; -- ------------------------------ -- Register the method definition in the table -- ------------------------------ procedure Register_Operation (Table : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Operation : Gen.Model.Operations.Operation_Definition_Access; begin Table.Add_Operation (Name, Operation); end Register_Operation; -- ------------------------------ -- Register all the operations defined in the table -- ------------------------------ procedure Register_Operations (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Operation); begin Log.Debug ("Register operations from bean {0}", Table.Name); Iterate (Table, Node, "method"); end Register_Operations; -- ------------------------------ -- Register the column definition in the table -- ------------------------------ procedure Register_Column (Table : in out Query_Definition; Column : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Column, "name"); C : Column_Definition_Access; begin Table.Add_Column (Name, C); C.Initialize (Name, Column); C.Type_Name := To_Unbounded_String (Gen.Utils.Get_Normalized_Type (Column, "type")); C.Is_Inserted := False; C.Is_Updated := False; C.Not_Null := False; C.Unique := False; -- Construct the hash for this column mapping. Append (Hash, ",type="); Append (Hash, C.Type_Name); Append (Hash, ",name="); Append (Hash, Name); end Register_Column; -- ------------------------------ -- Register all the columns defined in the table -- ------------------------------ procedure Register_Columns (Table : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Column); begin Log.Debug ("Register columns from query {0}", Table.Name); Iterate (Table, Node, "property"); end Register_Columns; -- ------------------------------ -- Register the sort definition in the query -- ------------------------------ procedure Register_Sort (Query : in out Query_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); Sql : constant String := Gen.Utils.Get_Data_Content (Node); begin Query.Add_Sort (Name, To_Unbounded_String (Sql)); end Register_Sort; -- ------------------------------ -- Register all the sort modes defined in the query -- ------------------------------ procedure Register_Sorts (Query : in out Query_Definition; Node : in DOM.Core.Node) is procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition, Process => Register_Sort); begin Log.Debug ("Register sorts from query {0}", Query.Name); Iterate (Query, Node, "order"); end Register_Sorts; -- ------------------------------ -- Register a new class definition in the model. -- ------------------------------ procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); begin Query.Initialize (Name, Node); Query.Set_Table_Name (To_String (Name)); if Name /= "" then Query.Name := Name; else Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path)); end if; -- Construct the hash for this column mapping. Append (Hash, "class="); Append (Hash, Query.Name); Log.Debug ("Register query {0} with type {1}", Query.Name, Query.Type_Name); Register_Columns (Query_Definition (Query), Node); Register_Operations (Query_Definition (Query), Node); end Register_Mapping; -- ------------------------------ -- Register a new query. -- ------------------------------ procedure Register_Query (Query : in out Gen.Model.Queries.Query_File_Definition; Node : in DOM.Core.Node) is Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "name"); C : Gen.Model.Queries.Query_Definition_Access; begin Query.Add_Query (Name, C); Register_Sorts (Query_Definition (C.all), Node); end Register_Query; -- ------------------------------ -- Register a model mapping -- ------------------------------ procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition; Node : in DOM.Core.Node) is procedure Iterate_Mapping is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Mapping); procedure Iterate_Query is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_File_Definition, Process => Register_Query); Table : constant Query_File_Definition_Access := new Query_File_Definition; Pkg : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "package"); Name : constant Unbounded_String := Gen.Utils.Get_Attribute (Node, "table"); begin Table.Initialize (Name, Node); Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path)); Table.Pkg_Name := Pkg; Iterate_Mapping (Query_File_Definition (Table.all), Node, "class"); Iterate_Query (Query_File_Definition (Table.all), Node, "query"); if Length (Table.Pkg_Name) = 0 then Context.Error ("Missing or empty package attribute"); else Model.Register_Query (Table); end if; Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash)); Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries", Data => To_String (Hash)); end Register_Mapping; procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition, Process => Register_Mapping); begin Log.Debug ("Initializing query artifact for the configuration"); Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context); Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping"); end Initialize; -- ------------------------------ -- Prepare the generation of the package: -- o identify the column types which are used -- o build a list of package for the with clauses. -- ------------------------------ overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is pragma Unreferenced (Handler); begin Log.Debug ("Preparing the model for query"); if Model.Has_Packages then Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE, Mapping => Gen.Model.Mappings.ADA_MAPPING); end if; end Prepare; end Gen.Artifacts.Query;
Add support for query bean operations - Declare and implement Register_Operation and Register_Operations - After registering the query columns, register its operations
Add support for query bean operations - Declare and implement Register_Operation and Register_Operations - After registering the query columns, register its operations
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo