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
fa0fd2bf2345c460254a0ed2228ba410719a3cbf
mat/src/mat.ads
mat/src/mat.ads
----------------------------------------------------------------------- -- mat -- Memory Analysis Tool -- 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 MAT is pragma Pure; end MAT;
----------------------------------------------------------------------- -- mat -- Memory Analysis Tool -- Copyright (C) 2014, 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. ----------------------------------------------------------------------- package MAT is private -- Configure the logs. procedure Configure_Logs (Debug : in Boolean; Dump : in Boolean; Verbose : in Boolean); end MAT;
Declare Configure_Logs procedure
Declare Configure_Logs procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3f8ff53de96af11f64270d69b673b39fd98610f3
src/ado-sessions-factory.adb
src/ado-sessions-factory.adb
----------------------------------------------------------------------- -- factory -- Session Factory -- 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 ADO.Sequences.Hilo; -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. package body ADO.Sessions.Factory is use ADO.Databases; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; S.Database := Master_Connection (DB); S.Entities := Factory.Entities; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Databases.DataSource) is begin Factory.Source := Source; Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. package body ADO.Sessions.Factory is use ADO.Databases; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; S.Database := Master_Connection (DB); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Databases.DataSource) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; end ADO.Sessions.Factory;
Initialize the cache group to register the entity_type cache
Initialize the cache group to register the entity_type cache
Ada
apache-2.0
stcarrez/ada-ado
b9c82704d04597a86f72a0d3dbe4d902e200818c
src/el-utils.adb
src/el-utils.adb
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name : in String; Item : in Util.Beans.Objects.Object); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then declare Value : constant String := Into.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name : in String; Item : in Util.Properties.Value) is use Ada.Strings; Value : constant String := Util.Properties.To_String (Item); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then Log.Debug ("Adding config {0} = {1}", Name, Value); Into.Set_Value (Name, Item); else declare New_Value : constant Object := Expand (Value, Local_Context); begin Log.Debug ("Adding config {0} = {1}", Name, Util.Beans.Objects.To_String (New_Value)); if Util.Beans.Objects.Is_Null (New_Value) then Into.Set (Name, ""); else Into.Set_Value (Name, New_Value); end if; end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name : in String; Item : in Util.Beans.Objects.Object); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then declare Value : constant String := Into.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name : in String; Item : in Util.Properties.Value) is Value : constant String := Util.Properties.To_String (Item); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then Log.Debug ("Adding config {0} = {1}", Name, Value); Into.Set_Value (Name, Item); else declare New_Value : constant Object := Expand (Value, Local_Context); begin Log.Debug ("Adding config {0} = {1}", Name, Util.Beans.Objects.To_String (New_Value)); if Util.Beans.Objects.Is_Null (New_Value) then Into.Set (Name, ""); else Into.Set_Value (Name, New_Value); end if; end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
Remove unecessary use Ada.Strings clause
Remove unecessary use Ada.Strings clause
Ada
apache-2.0
stcarrez/ada-el
26df3b20033f29e716247d33b920b06b9fe0bf31
src/gl/interface/gl-objects-textures.ads
src/gl/interface/gl-objects-textures.ads
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System; with Interfaces.C.Pointers; with Ada.Unchecked_Deallocation; with GL.Low_Level.Enums; with GL.Objects.Buffers; with GL.Pixels.Extensions; with GL.Types.Colors; package GL.Objects.Textures is pragma Preelaborate; package LE renames Low_Level.Enums; package PE renames Pixels.Extensions; type Dimension_Count is (One, Two, Three); function Get_Dimensions (Kind : LE.Texture_Kind) return Dimension_Count; function Maximum_Anisotropy return Single with Post => Maximum_Anisotropy'Result >= 16.0; ----------------------------------------------------------------------------- -- Basic Types -- ----------------------------------------------------------------------------- type Minifying_Function is (Nearest, Linear, Nearest_Mipmap_Nearest, Linear_Mipmap_Nearest, Nearest_Mipmap_Linear, Linear_Mipmap_Linear); -- Has to be defined here because of following subtype declaration. for Minifying_Function use (Nearest => 16#2600#, Linear => 16#2601#, Nearest_Mipmap_Nearest => 16#2700#, Linear_Mipmap_Nearest => 16#2701#, Nearest_Mipmap_Linear => 16#2702#, Linear_Mipmap_Linear => 16#2703#); for Minifying_Function'Size use Int'Size; subtype Magnifying_Function is Minifying_Function range Nearest .. Linear; type Wrapping_Mode is (Repeat, Clamp_To_Border, Clamp_To_Edge, Mirrored_Repeat); -- Actual range is implementation-defined -- -- - OpenGL 2.x: At least 2 -- - OpenGL 3.x: At least 48 -- - OpenGL 4.x: At least 80 subtype Texture_Unit is UInt; subtype Image_Unit is UInt; subtype Mipmap_Level is Size; ----------------------------------------------------------------------------- -- Texture Objects -- ----------------------------------------------------------------------------- type Texture_Base (Kind : LE.Texture_Kind) is abstract new GL_Object with private; use type LE.Texture_Kind; function Has_Levels (Object : Texture_Base) return Boolean is (Object.Kind not in LE.Texture_Buffer | LE.Texture_Rectangle | LE.Texture_2D_Multisample | LE.Texture_2D_Multisample_Array) with Inline; overriding procedure Initialize_Id (Object : in out Texture_Base); overriding procedure Delete_Id (Object : in out Texture_Base); overriding function Identifier (Object : Texture_Base) return Types.Debug.Identifier is (Types.Debug.Texture); procedure Invalidate_Image (Object : Texture_Base; Level : Mipmap_Level) with Pre => (if not Object.Has_Levels then Level = 0); procedure Invalidate_Sub_Image (Object : Texture_Base; Level : Mipmap_Level; X, Y, Z : Int; Width, Height, Depth : Size) with Pre => (if not Object.Has_Levels then Level = 0); procedure Bind_Texture_Unit (Object : Texture_Base; Unit : Texture_Unit); procedure Bind_Image_Texture (Object : Texture_Base; Unit : Image_Unit); ----------------------------------------------------------------------------- type Texture is new Texture_Base with private; function Dimensions (Object : Texture) return Dimension_Count; function Allocated (Object : Texture) return Boolean; procedure Clear_Using_Data (Object : Texture; Level : Mipmap_Level; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) with Pre => not Object.Compressed (Level); procedure Clear_Using_Zeros (Object : Texture; Level : Mipmap_Level) with Pre => not Object.Compressed (Level); procedure Generate_Mipmap (Object : Texture); ----------------------------------------------------------------------------- -- Texture Parameters -- ----------------------------------------------------------------------------- procedure Set_Minifying_Filter (Object : Texture; Filter : Minifying_Function); procedure Set_Magnifying_Filter (Object : Texture; Filter : Magnifying_Function); procedure Set_Minimum_LoD (Object : Texture; Level : Double); procedure Set_Maximum_LoD (Object : Texture; Level : Double); procedure Set_Lowest_Mipmap_Level (Object : Texture; Level : Mipmap_Level); procedure Set_Highest_Mipmap_Level (Object : Texture; Level : Mipmap_Level); function Minifying_Filter (Object : Texture) return Minifying_Function; function Magnifying_Filter (Object : Texture) return Magnifying_Function; function Minimum_LoD (Object : Texture) return Double; function Maximum_LoD (Object : Texture) return Double; function Lowest_Mipmap_Level (Object : Texture) return Mipmap_Level; function Highest_Mipmap_Level (Object : Texture) return Mipmap_Level; -- TODO LoD_Bias (Double) procedure Set_Max_Anisotropy (Object : Texture; Degree : Double) with Pre => Degree >= 1.0; -- Set the maximum amount of anisotropy filtering to reduce the blurring -- of textures (caused by mipmap filtering) that are viewed at an -- oblique angle. -- -- For best results, combine the use of anisotropy filtering with -- a Linear_Mipmap_Linear minification filter and a Linear maxification -- filter. function Max_Anisotropy (Object : Texture) return Double with Post => Max_Anisotropy'Result >= 1.0; procedure Set_X_Wrapping (Object : Texture; Mode : Wrapping_Mode); procedure Set_Y_Wrapping (Object : Texture; Mode : Wrapping_Mode); procedure Set_Z_Wrapping (Object : Texture; Mode : Wrapping_Mode); function X_Wrapping (Object : Texture) return Wrapping_Mode; function Y_Wrapping (Object : Texture) return Wrapping_Mode; function Z_Wrapping (Object : Texture) return Wrapping_Mode; procedure Set_Border_Color (Object : Texture; Color : Colors.Color); function Border_Color (Object : Texture) return Colors.Color; procedure Toggle_Compare_X_To_Texture (Object : Texture; Enabled : Boolean); procedure Set_Compare_Function (Object : Texture; Func : Compare_Function); function Compare_X_To_Texture_Enabled (Object : Texture) return Boolean; function Current_Compare_Function (Object : Texture) return Compare_Function; ----------------------------------------------------------------------------- -- Texture Level Parameters -- ----------------------------------------------------------------------------- function Width (Object : Texture; Level : Mipmap_Level) return Size; function Height (Object : Texture; Level : Mipmap_Level) return Size; function Depth (Object : Texture; Level : Mipmap_Level) return Size; function Internal_Format (Object : Texture; Level : Mipmap_Level) return Pixels.Internal_Format with Pre => Object.Allocated and not Object.Compressed (Level); function Compressed_Format (Object : Texture; Level : Mipmap_Level) return Pixels.Compressed_Format with Pre => Object.Allocated and Object.Compressed (Level); function Red_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Green_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Blue_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Alpha_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Depth_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Red_Size (Object : Texture; Level : Mipmap_Level) return Size; function Green_Size (Object : Texture; Level : Mipmap_Level) return Size; function Blue_Size (Object : Texture; Level : Mipmap_Level) return Size; function Alpha_Size (Object : Texture; Level : Mipmap_Level) return Size; function Depth_Size (Object : Texture; Level : Mipmap_Level) return Size; -- TODO Stencil_Size, Shared_Size function Compressed (Object : Texture; Level : Mipmap_Level) return Boolean; function Compressed_Image_Size (Object : Texture; Level : Mipmap_Level) return Size; -- TODO Pre => Object is compressed -- TODO Samples (Size), Fixed_Sample_Locations (Boolean) (if Object is multisampled) function Buffer_Offset (Object : Texture; Level : Mipmap_Level) return Size; function Buffer_Size (Object : Texture; Level : Mipmap_Level) return Size; ----------------------------------------------------------------------------- -- Texture Units -- ----------------------------------------------------------------------------- function Active_Unit return Texture_Unit; function Texture_Unit_Count return Natural; ----------------------------------------------------------------------------- -- Buffer Texture Loading -- ----------------------------------------------------------------------------- type Buffer_Texture is new Texture_Base (Kind => LE.Texture_Buffer) with private; procedure Attach_Buffer (Object : Buffer_Texture; Internal_Format : Pixels.Internal_Format_Buffer_Texture; Buffer : Objects.Buffers.Buffer); procedure Attach_Buffer (Object : Buffer_Texture; Internal_Format : Pixels.Internal_Format_Buffer_Texture; Buffer : Objects.Buffers.Buffer; Offset, Size : Types.Size); ----------------------------------------------------------------------------- -- Texture Loading -- ----------------------------------------------------------------------------- procedure Allocate_Storage (Object : in out Texture; Levels, Samples : Types.Size; Format : Pixels.Internal_Format; Width, Height, Depth : Types.Size; Fixed_Locations : Boolean := True) with Pre => not Object.Allocated, Post => Object.Allocated; procedure Allocate_Storage (Object : in out Texture; Levels, Samples : Types.Size; Format : Pixels.Compressed_Format; Width, Height, Depth : Types.Size; Fixed_Locations : Boolean := True) with Pre => not Object.Allocated and Object.Kind /= LE.Texture_Rectangle, Post => Object.Allocated; procedure Load_From_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) with Pre => Object.Allocated and not Object.Compressed (Level); procedure Load_From_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Compressed_Format; Image_Size : Types.Size; Source : System.Address) with Pre => Object.Dimensions /= One and Object.Allocated and Object.Compressed (Level); procedure Copy_Data (Object : Texture; Subject : Texture; Source_Level, Target_Level : Mipmap_Level) with Pre => Object.Allocated and Subject.Allocated; procedure Copy_Sub_Data (Object : Texture; Subject : Texture; Source_Level, Target_Level : Mipmap_Level; Source_X, Source_Y, Source_Z : Types.Size := 0; Target_X, Target_Y, Target_Z : Types.Size := 0; Width, Height, Depth : Types.Size) with Pre => Object.Allocated and Subject.Allocated; procedure Clear_Using_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) with Pre => not Object.Compressed (Level); procedure Clear_Using_Zeros (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size) with Pre => not Object.Compressed (Level); ----------------------------------------------------------------------------- function Get_Compressed_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Format : Pixels.Compressed_Format) return not null Types.UByte_Array_Access with Pre => Object.Dimensions /= One and Object.Allocated and Object.Compressed (Level) and Object.Kind not in LE.Texture_2D_Multisample | LE.Texture_2D_Multisample_Array; generic with package Pointers is new Interfaces.C.Pointers (<>); package Texture_Pointers is type Element_Array_Access is access Pointers.Element_Array; procedure Free is new Ada.Unchecked_Deallocation (Object => Pointers.Element_Array, Name => Element_Array_Access); function Get_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Format : Pixels.Format; Data_Type : PE.Non_Packed_Data_Type) return not null Element_Array_Access with Pre => Object.Allocated and not Object.Compressed (Level) and PE.Compatible (Format, Data_Type); end Texture_Pointers; private for Wrapping_Mode use (Repeat => 16#2901#, Clamp_To_Border => 16#812D#, Clamp_To_Edge => 16#812F#, Mirrored_Repeat => 16#8370#); for Wrapping_Mode'Size use Int'Size; type Texture_Base (Kind : LE.Texture_Kind) is new GL_Object with null record; type Texture is new Texture_Base with record Allocated : Boolean := False; Dimensions : Dimension_Count := Get_Dimensions (Texture.Kind); end record; type Buffer_Texture is new Texture_Base (Kind => LE.Texture_Buffer) with null record; end GL.Objects.Textures;
-- Copyright (c) 2012 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System; with Interfaces.C.Pointers; with Ada.Unchecked_Deallocation; with GL.Low_Level.Enums; with GL.Objects.Buffers; with GL.Pixels.Extensions; with GL.Types.Colors; package GL.Objects.Textures is pragma Preelaborate; package LE renames Low_Level.Enums; package PE renames Pixels.Extensions; type Dimension_Count is (One, Two, Three); function Get_Dimensions (Kind : LE.Texture_Kind) return Dimension_Count; function Maximum_Anisotropy return Single with Post => Maximum_Anisotropy'Result >= 16.0; ----------------------------------------------------------------------------- -- Basic Types -- ----------------------------------------------------------------------------- type Minifying_Function is (Nearest, Linear, Nearest_Mipmap_Nearest, Linear_Mipmap_Nearest, Nearest_Mipmap_Linear, Linear_Mipmap_Linear); -- Has to be defined here because of following subtype declaration. for Minifying_Function use (Nearest => 16#2600#, Linear => 16#2601#, Nearest_Mipmap_Nearest => 16#2700#, Linear_Mipmap_Nearest => 16#2701#, Nearest_Mipmap_Linear => 16#2702#, Linear_Mipmap_Linear => 16#2703#); for Minifying_Function'Size use Int'Size; subtype Magnifying_Function is Minifying_Function range Nearest .. Linear; type Wrapping_Mode is (Repeat, Clamp_To_Border, Clamp_To_Edge, Mirrored_Repeat, Mirror_Clamp_To_Edge); -- Actual range is implementation-defined -- -- - OpenGL 2.x: At least 2 -- - OpenGL 3.x: At least 48 -- - OpenGL 4.x: At least 80 subtype Texture_Unit is UInt; subtype Image_Unit is UInt; subtype Mipmap_Level is Size; ----------------------------------------------------------------------------- -- Texture Objects -- ----------------------------------------------------------------------------- type Texture_Base (Kind : LE.Texture_Kind) is abstract new GL_Object with private; use type LE.Texture_Kind; function Has_Levels (Object : Texture_Base) return Boolean is (Object.Kind not in LE.Texture_Buffer | LE.Texture_Rectangle | LE.Texture_2D_Multisample | LE.Texture_2D_Multisample_Array) with Inline; overriding procedure Initialize_Id (Object : in out Texture_Base); overriding procedure Delete_Id (Object : in out Texture_Base); overriding function Identifier (Object : Texture_Base) return Types.Debug.Identifier is (Types.Debug.Texture); procedure Invalidate_Image (Object : Texture_Base; Level : Mipmap_Level) with Pre => (if not Object.Has_Levels then Level = 0); procedure Invalidate_Sub_Image (Object : Texture_Base; Level : Mipmap_Level; X, Y, Z : Int; Width, Height, Depth : Size) with Pre => (if not Object.Has_Levels then Level = 0); procedure Bind_Texture_Unit (Object : Texture_Base; Unit : Texture_Unit); procedure Bind_Image_Texture (Object : Texture_Base; Unit : Image_Unit); ----------------------------------------------------------------------------- type Texture is new Texture_Base with private; function Dimensions (Object : Texture) return Dimension_Count; function Allocated (Object : Texture) return Boolean; procedure Clear_Using_Data (Object : Texture; Level : Mipmap_Level; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) with Pre => not Object.Compressed (Level); procedure Clear_Using_Zeros (Object : Texture; Level : Mipmap_Level) with Pre => not Object.Compressed (Level); procedure Generate_Mipmap (Object : Texture); ----------------------------------------------------------------------------- -- Texture Parameters -- ----------------------------------------------------------------------------- procedure Set_Minifying_Filter (Object : Texture; Filter : Minifying_Function); procedure Set_Magnifying_Filter (Object : Texture; Filter : Magnifying_Function); procedure Set_Minimum_LoD (Object : Texture; Level : Double); procedure Set_Maximum_LoD (Object : Texture; Level : Double); procedure Set_Lowest_Mipmap_Level (Object : Texture; Level : Mipmap_Level); procedure Set_Highest_Mipmap_Level (Object : Texture; Level : Mipmap_Level); function Minifying_Filter (Object : Texture) return Minifying_Function; function Magnifying_Filter (Object : Texture) return Magnifying_Function; function Minimum_LoD (Object : Texture) return Double; function Maximum_LoD (Object : Texture) return Double; function Lowest_Mipmap_Level (Object : Texture) return Mipmap_Level; function Highest_Mipmap_Level (Object : Texture) return Mipmap_Level; -- TODO LoD_Bias (Double) procedure Set_Max_Anisotropy (Object : Texture; Degree : Double) with Pre => Degree >= 1.0; -- Set the maximum amount of anisotropy filtering to reduce the blurring -- of textures (caused by mipmap filtering) that are viewed at an -- oblique angle. -- -- For best results, combine the use of anisotropy filtering with -- a Linear_Mipmap_Linear minification filter and a Linear maxification -- filter. function Max_Anisotropy (Object : Texture) return Double with Post => Max_Anisotropy'Result >= 1.0; procedure Set_X_Wrapping (Object : Texture; Mode : Wrapping_Mode); procedure Set_Y_Wrapping (Object : Texture; Mode : Wrapping_Mode); procedure Set_Z_Wrapping (Object : Texture; Mode : Wrapping_Mode); function X_Wrapping (Object : Texture) return Wrapping_Mode; function Y_Wrapping (Object : Texture) return Wrapping_Mode; function Z_Wrapping (Object : Texture) return Wrapping_Mode; procedure Set_Border_Color (Object : Texture; Color : Colors.Color); function Border_Color (Object : Texture) return Colors.Color; procedure Toggle_Compare_X_To_Texture (Object : Texture; Enabled : Boolean); procedure Set_Compare_Function (Object : Texture; Func : Compare_Function); function Compare_X_To_Texture_Enabled (Object : Texture) return Boolean; function Current_Compare_Function (Object : Texture) return Compare_Function; ----------------------------------------------------------------------------- -- Texture Level Parameters -- ----------------------------------------------------------------------------- function Width (Object : Texture; Level : Mipmap_Level) return Size; function Height (Object : Texture; Level : Mipmap_Level) return Size; function Depth (Object : Texture; Level : Mipmap_Level) return Size; function Internal_Format (Object : Texture; Level : Mipmap_Level) return Pixels.Internal_Format with Pre => Object.Allocated and not Object.Compressed (Level); function Compressed_Format (Object : Texture; Level : Mipmap_Level) return Pixels.Compressed_Format with Pre => Object.Allocated and Object.Compressed (Level); function Red_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Green_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Blue_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Alpha_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Depth_Type (Object : Texture; Level : Mipmap_Level) return Pixels.Channel_Data_Type; function Red_Size (Object : Texture; Level : Mipmap_Level) return Size; function Green_Size (Object : Texture; Level : Mipmap_Level) return Size; function Blue_Size (Object : Texture; Level : Mipmap_Level) return Size; function Alpha_Size (Object : Texture; Level : Mipmap_Level) return Size; function Depth_Size (Object : Texture; Level : Mipmap_Level) return Size; -- TODO Stencil_Size, Shared_Size function Compressed (Object : Texture; Level : Mipmap_Level) return Boolean; function Compressed_Image_Size (Object : Texture; Level : Mipmap_Level) return Size; -- TODO Pre => Object is compressed -- TODO Samples (Size), Fixed_Sample_Locations (Boolean) (if Object is multisampled) function Buffer_Offset (Object : Texture; Level : Mipmap_Level) return Size; function Buffer_Size (Object : Texture; Level : Mipmap_Level) return Size; ----------------------------------------------------------------------------- -- Texture Units -- ----------------------------------------------------------------------------- function Active_Unit return Texture_Unit; function Texture_Unit_Count return Natural; ----------------------------------------------------------------------------- -- Buffer Texture Loading -- ----------------------------------------------------------------------------- type Buffer_Texture is new Texture_Base (Kind => LE.Texture_Buffer) with private; procedure Attach_Buffer (Object : Buffer_Texture; Internal_Format : Pixels.Internal_Format_Buffer_Texture; Buffer : Objects.Buffers.Buffer); procedure Attach_Buffer (Object : Buffer_Texture; Internal_Format : Pixels.Internal_Format_Buffer_Texture; Buffer : Objects.Buffers.Buffer; Offset, Size : Types.Size); ----------------------------------------------------------------------------- -- Texture Loading -- ----------------------------------------------------------------------------- procedure Allocate_Storage (Object : in out Texture; Levels, Samples : Types.Size; Format : Pixels.Internal_Format; Width, Height, Depth : Types.Size; Fixed_Locations : Boolean := True) with Pre => not Object.Allocated, Post => Object.Allocated; procedure Allocate_Storage (Object : in out Texture; Levels, Samples : Types.Size; Format : Pixels.Compressed_Format; Width, Height, Depth : Types.Size; Fixed_Locations : Boolean := True) with Pre => not Object.Allocated and Object.Kind /= LE.Texture_Rectangle, Post => Object.Allocated; procedure Load_From_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) with Pre => Object.Allocated and not Object.Compressed (Level); procedure Load_From_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Compressed_Format; Image_Size : Types.Size; Source : System.Address) with Pre => Object.Dimensions /= One and Object.Allocated and Object.Compressed (Level); procedure Copy_Data (Object : Texture; Subject : Texture; Source_Level, Target_Level : Mipmap_Level) with Pre => Object.Allocated and Subject.Allocated; procedure Copy_Sub_Data (Object : Texture; Subject : Texture; Source_Level, Target_Level : Mipmap_Level; Source_X, Source_Y, Source_Z : Types.Size := 0; Target_X, Target_Y, Target_Z : Types.Size := 0; Width, Height, Depth : Types.Size) with Pre => Object.Allocated and Subject.Allocated; procedure Clear_Using_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Source_Format : Pixels.Format; Source_Type : Pixels.Data_Type; Source : System.Address) with Pre => not Object.Compressed (Level); procedure Clear_Using_Zeros (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size) with Pre => not Object.Compressed (Level); ----------------------------------------------------------------------------- function Get_Compressed_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Format : Pixels.Compressed_Format) return not null Types.UByte_Array_Access with Pre => Object.Dimensions /= One and Object.Allocated and Object.Compressed (Level) and Object.Kind not in LE.Texture_2D_Multisample | LE.Texture_2D_Multisample_Array; generic with package Pointers is new Interfaces.C.Pointers (<>); package Texture_Pointers is type Element_Array_Access is access Pointers.Element_Array; procedure Free is new Ada.Unchecked_Deallocation (Object => Pointers.Element_Array, Name => Element_Array_Access); function Get_Data (Object : Texture; Level : Mipmap_Level; X, Y, Z : Types.Size := 0; Width, Height, Depth : Types.Positive_Size; Format : Pixels.Format; Data_Type : PE.Non_Packed_Data_Type) return not null Element_Array_Access with Pre => Object.Allocated and not Object.Compressed (Level) and PE.Compatible (Format, Data_Type); end Texture_Pointers; private for Wrapping_Mode use (Repeat => 16#2901#, Clamp_To_Border => 16#812D#, Clamp_To_Edge => 16#812F#, Mirrored_Repeat => 16#8370#, Mirror_Clamp_To_Edge => 16#8743#); for Wrapping_Mode'Size use Int'Size; type Texture_Base (Kind : LE.Texture_Kind) is new GL_Object with null record; type Texture is new Texture_Base with record Allocated : Boolean := False; Dimensions : Dimension_Count := Get_Dimensions (Texture.Kind); end record; type Buffer_Texture is new Texture_Base (Kind => LE.Texture_Buffer) with null record; end GL.Objects.Textures;
Add Mirror_Clamp_To_Edge texture wrapping mode
gl: Add Mirror_Clamp_To_Edge texture wrapping mode * Extension ARB_texture_mirror_clamp_to_edge (OpenGL 4.4) Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
fb5919fc1d9ce2e8579af649863a297a541fec45
src/atlas-applications.ads
src/atlas-applications.ads
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Filters.Cache_Control; with ASF.Servlets.Measures; with ASF.Security.Servlets; with ASF.Converters.Sizes; with ASF.Applications; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Wikis.Modules; with AWA.Wikis.Previews; with AWA.Jobs.Modules; with AWA.Counters.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Comments.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; with Atlas.Reviews.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- 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_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access; Config : in ASF.Applications.Config); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; No_Cache : aliased ASF.Filters.Cache_Control.Cache_Control_Filter; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Size_Converter : aliased ASF.Converters.Sizes.Size_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Job_Module : aliased AWA.Jobs.Modules.Job_Module; Storage_Module : aliased AWA.Storages.Modules.Storage_Module; Image_Module : aliased AWA.Images.Modules.Image_Module; Vote_Module : aliased AWA.Votes.Modules.Vote_Module; Question_Module : aliased AWA.Questions.Modules.Question_Module; Tag_Module : aliased AWA.Tags.Modules.Tag_Module; Comment_Module : aliased AWA.Comments.Modules.Comment_Module; Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module; Preview_Module : aliased AWA.Wikis.Previews.Preview_Module; Counter_Module : aliased AWA.Counters.Modules.Counter_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; Review_Module : aliased Atlas.Reviews.Modules.Review_Module; end record; end Atlas.Applications;
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 2012, 2013, 2014, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Servlets.Faces; with Servlet.Core.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Filters.Cache_Control; with Servlet.Core.Measures; with ASF.Security.Servlets; with ASF.Converters.Sizes; with ASF.Applications; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Wikis.Modules; with AWA.Wikis.Previews; with AWA.Jobs.Modules; with AWA.Counters.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Comments.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; with Atlas.Reviews.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- 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_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access; Config : in ASF.Applications.Config); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased Servlet.Core.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased Servlet.Core.Measures.Measure_Servlet; No_Cache : aliased ASF.Filters.Cache_Control.Cache_Control_Filter; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Size_Converter : aliased ASF.Converters.Sizes.Size_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Job_Module : aliased AWA.Jobs.Modules.Job_Module; Storage_Module : aliased AWA.Storages.Modules.Storage_Module; Image_Module : aliased AWA.Images.Modules.Image_Module; Vote_Module : aliased AWA.Votes.Modules.Vote_Module; Question_Module : aliased AWA.Questions.Modules.Question_Module; Tag_Module : aliased AWA.Tags.Modules.Tag_Module; Comment_Module : aliased AWA.Comments.Modules.Comment_Module; Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module; Preview_Module : aliased AWA.Wikis.Previews.Preview_Module; Counter_Module : aliased AWA.Counters.Modules.Counter_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; Review_Module : aliased Atlas.Reviews.Modules.Review_Module; end record; end Atlas.Applications;
Update to use the Servlet.Core package after migration of servlet in a separate project
Update to use the Servlet.Core package after migration of servlet in a separate project
Ada
apache-2.0
stcarrez/atlas
375422d7e98bed612b5d085c34c18fb285d3e8cd
regtests/util-strings-tests.ads
regtests/util-strings-tests.ads
----------------------------------------------------------------------- -- strings.tests -- Unit tests for Strings -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- 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_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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES 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;
Declare Test_Escape_Java procedure
Declare Test_Escape_Java procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d7df322da9520f2036c93acc189e358c77d02c9c
src/security-permissions.adb
src/security-permissions.adb
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Log.Loggers; -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package body Security.Permissions is -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Permissions"); -- A global map to translate a string to a permission index. package Permission_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Permission_Index, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); protected type Global_Index is -- Get the permission index function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index); private Map : Permission_Maps.Map; Next_Index : Permission_Index := NONE + 1; end Global_Index; protected body Global_Index is function Get_Permission_Index (Name : in String) return Permission_Index is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then return Permission_Maps.Element (Pos); else raise Invalid_Name with "There is no permission '" & Name & "'"; end if; end Get_Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index is begin return Next_Index; end Get_Last_Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index) is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then Index := Permission_Maps.Element (Pos); else Index := Next_Index; Log.Debug ("Creating permission index {1} for {0}", Name, Permission_Index'Image (Index)); Map.Insert (Name, Index); if Next_Index = Permission_Index'Last then Log.Error ("Too many permission instantiated. " & "Increase Security.Permissions.MAX_PERMISSION"); else Next_Index := Next_Index + 1; end if; end if; end Add_Permission; end Global_Index; Permission_Indexes : Global_Index; -- ------------------------------ -- Get the permission index associated with the name. -- ------------------------------ function Get_Permission_Index (Name : in String) return Permission_Index is begin return Permission_Indexes.Get_Permission_Index (Name); end Get_Permission_Index; -- ------------------------------ -- Get the last permission index registered in the global permission map. -- ------------------------------ function Get_Last_Permission_Index return Permission_Index is begin return Permission_Indexes.Get_Last_Permission_Index; end Get_Last_Permission_Index; -- ------------------------------ -- Add the permission name and allocate a unique permission index. -- ------------------------------ procedure Add_Permission (Name : in String; Index : out Permission_Index) is begin Permission_Indexes.Add_Permission (Name, Index); end Add_Permission; -- ------------------------------ -- Check if the permission index set contains the given permission index. -- ------------------------------ function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean is use Interfaces; begin return (Set (Natural (Index / 8)) and Shift_Left (1, Natural (Index mod 8))) /= 0; end Has_Permission; -- ------------------------------ -- Add the permission index to the set. -- ------------------------------ procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index) is use Interfaces; Pos : constant Natural := Natural (Index / 8); begin Set (Pos) := Set (Pos) or Shift_Left (1, Natural (Index mod 8)); end Add_Permission; package body Definition is P : Permission_Index; function Permission return Permission_Index is begin return P; end Permission; begin Add_Permission (Name => Name, Index => P); end Definition; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Log.Loggers; -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package body Security.Permissions is -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Permissions"); -- A global map to translate a string to a permission index. package Permission_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Permission_Index, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); protected type Global_Index is -- Get the permission index function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Get the permission name associated with the index. function Get_Name (Index : in Permission_Index) return String; procedure Add_Permission (Name : in String; Index : out Permission_Index); private Map : Permission_Maps.Map; Next_Index : Permission_Index := NONE + 1; end Global_Index; protected body Global_Index is function Get_Permission_Index (Name : in String) return Permission_Index is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then return Permission_Maps.Element (Pos); else raise Invalid_Name with "There is no permission '" & Name & "'"; end if; end Get_Permission_Index; -- ------------------------------ -- Get the last permission index registered in the global permission map. -- ------------------------------ function Get_Last_Permission_Index return Permission_Index is begin return Next_Index - 1; end Get_Last_Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index) is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then Index := Permission_Maps.Element (Pos); else Index := Next_Index; Log.Debug ("Creating permission index {1} for {0}", Name, Permission_Index'Image (Index)); Map.Insert (Name, Index); if Next_Index = Permission_Index'Last then Log.Error ("Too many permission instantiated. " & "Increase Security.Permissions.MAX_PERMISSION"); else Next_Index := Next_Index + 1; end if; end if; end Add_Permission; -- ------------------------------ -- Get the permission name associated with the index. -- ------------------------------ function Get_Name (Index : in Permission_Index) return String is Iter : Permission_Maps.Cursor := Map.First; begin while Permission_Maps.Has_Element (Iter) loop if Permission_Maps.Element (Iter) = Index then return Permission_Maps.Key (Iter); end if; Permission_Maps.Next (Iter); end loop; return ""; end Get_Name; end Global_Index; Permission_Indexes : Global_Index; -- ------------------------------ -- Get the permission index associated with the name. -- ------------------------------ function Get_Permission_Index (Name : in String) return Permission_Index is begin return Permission_Indexes.Get_Permission_Index (Name); end Get_Permission_Index; -- ------------------------------ -- Get the permission name given the index. -- ------------------------------ function Get_Name (Index : in Permission_Index) return String is begin return Permission_Indexes.Get_Name (Index); end Get_Name; -- ------------------------------ -- Get the last permission index registered in the global permission map. -- ------------------------------ function Get_Last_Permission_Index return Permission_Index is begin return Permission_Indexes.Get_Last_Permission_Index; end Get_Last_Permission_Index; -- ------------------------------ -- Add the permission name and allocate a unique permission index. -- ------------------------------ procedure Add_Permission (Name : in String; Index : out Permission_Index) is begin Permission_Indexes.Add_Permission (Name, Index); end Add_Permission; -- ------------------------------ -- Check if the permission index set contains the given permission index. -- ------------------------------ function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean is use Interfaces; begin return (Set (Natural (Index / 8)) and Shift_Left (1, Natural (Index mod 8))) /= 0; end Has_Permission; -- ------------------------------ -- Add the permission index to the set. -- ------------------------------ procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index) is use Interfaces; Pos : constant Natural := Natural (Index / 8); begin Set (Pos) := Set (Pos) or Shift_Left (1, Natural (Index mod 8)); end Add_Permission; package body Definition is P : Permission_Index; function Permission return Permission_Index is begin return P; end Permission; begin Add_Permission (Name => Name, Index => P); end Definition; end Security.Permissions;
Declare and implement the Get_Name protected operation Implement the Get_Name public function
Declare and implement the Get_Name protected operation Implement the Get_Name public function
Ada
apache-2.0
stcarrez/ada-security
af801dc6f45c2337953121cbad39d6304f9390df
src/util-beans-factory.adb
src/util-beans-factory.adb
----------------------------------------------------------------------- -- Util.beans.factory -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 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; package body Util.Beans.Factory is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Beans.Factory"); -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Definition : in Bean_Definition_Access; Scope : in Scope_Type := REQUEST_SCOPE) is B : constant Simple_Binding_Access := new Simple_Binding '(Def => Definition, Scope => Scope); begin Log.Info ("Register bean '{0}' in scope {1}", Name, Scope_Type'Image (Scope)); Register (Factory, Name, B.all'Access); end Register; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Bind : in Binding_Access) is begin Log.Info ("Register bean binding '{0}'", Name); Factory.Map.Include (Key => To_Unbounded_String (Name), New_Item => Bind); 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 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 Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access; Definition : out Bean_Definition_Access; Scope : out Scope_Type) is Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare B : constant Binding_Access := Bean_Maps.Element (Pos); begin B.Create (Name, Result, Definition, Scope); end; end if; end Create; procedure Create (Factory : in Simple_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access; Definition : out Bean_Definition_Access; Scope : out Scope_Type) is pragma Unreferenced (Name); begin Result := Factory.Def.Create; Definition := Factory.Def; Scope := Factory.Scope; end Create; end Util.Beans.Factory;
----------------------------------------------------------------------- -- util-beans-factory -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body Util.Beans.Factory is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Beans.Factory"); -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Definition : in Bean_Definition_Access; Scope : in Scope_Type := REQUEST_SCOPE) is B : constant Simple_Binding_Access := new Simple_Binding '(Def => Definition, Scope => Scope); begin Log.Info ("Register bean '{0}' in scope {1}", Name, Scope_Type'Image (Scope)); Register (Factory, Name, B.all'Access); end Register; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Bind : in Binding_Access) is begin Log.Info ("Register bean binding '{0}'", Name); Factory.Map.Include (Key => To_Unbounded_String (Name), New_Item => Bind); 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 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 Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access; Definition : out Bean_Definition_Access; Scope : out Scope_Type) is Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare B : constant Binding_Access := Bean_Maps.Element (Pos); begin B.Create (Name, Result, Definition, Scope); end; end if; end Create; procedure Create (Factory : in Simple_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access; Definition : out Bean_Definition_Access; Scope : out Scope_Type) is pragma Unreferenced (Name); begin Result := Factory.Def.Create; Definition := Factory.Def; Scope := Factory.Scope; end Create; end Util.Beans.Factory;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
665c8dc28825d7fe0ebf254ec197701417fb373c
src/util-events-timers.adb
src/util-events-timers.adb
----------------------------------------------------------------------- -- util-events-timers -- Timer list 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.Unchecked_Deallocation; package body Util.Events.Timers is use type Ada.Real_Time.Time; procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin loop List.Manager.Find_Next (Now, Timeout, Timer); exit when Timer.Value = null; Timer.Value.Handler.Time_Handler (Timer); Timer.Finalize; end loop; end Process; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline < Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed before the given time or return the next deadline. -- ----------------------- procedure Find_Next (Before : in Ada.Real_Time.Time; Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is begin if List = null then Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Before then Timer.Value := List; List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is Timer : Timer_Ref; Timeout : Ada.Real_Time.Time; begin loop Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer); exit when Timer.Value = null; Timer.Finalize; end loop; end Finalize; end Util.Events.Timers;
----------------------------------------------------------------------- -- util-events-timers -- Timer list 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.Unchecked_Deallocation; package body Util.Events.Timers is use type Ada.Real_Time.Time; procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Set a timer to be called after the given time span. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; In_Time : in Ada.Real_Time.Time_Span) is begin List.Set_Timer (Handler, Event, Ada.Real_Time.Clock + In_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin loop List.Manager.Find_Next (Now, Timeout, Timer); exit when Timer.Value = null; Timer.Value.Handler.Time_Handler (Timer); Timer.Finalize; end loop; end Process; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline < Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed before the given time or return the next deadline. -- ----------------------- procedure Find_Next (Before : in Ada.Real_Time.Time; Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is begin if List = null then Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Before then Timer.Value := List; List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is Timer : Timer_Ref; Timeout : Ada.Real_Time.Time; begin loop Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer); exit when Timer.Value = null; Timer.Finalize; end loop; end Finalize; end Util.Events.Timers;
Implement the Set_Timer procedure which uses Time_Span as parameter
Implement the Set_Timer procedure which uses Time_Span as parameter
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
cd06059e47a0680aa5347aae37ee04389a0f94a7
src/babel-streams-cached.ads
src/babel-streams-cached.ads
----------------------------------------------------------------------- -- babel-Streams-cached -- Cached stream management -- 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. ----------------------------------------------------------------------- -- == Cached Stream == -- The <tt>Babel.Streams.Cached</tt> package provides a cached stream where the whole -- stream is read in one or several stream buffers. package Babel.Streams.Cached is type Stream_Type is new Babel.Streams.Stream_Type with private; type Stream_Access is access all Stream_Type'Class; -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. overriding procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access); -- Write the buffer in the data stream. overriding procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access); -- Flush the data stream. overriding procedure Flush (Stream : in out Stream_Type); -- Close the data stream. overriding procedure Close (Stream : in out Stream_Type); -- Prepare to read again the data stream from the beginning. overriding procedure Rewind (Stream : in out Stream_Type); private type Stream_Type is new Babel.Streams.Stream_Type with record Input : Babel.Streams.Stream_Access; Output : Babel.Streams.Stream_Access; Buffers : Babel.Files.Buffers.Buffer_Access_Vector; Current : Babel.Files.Buffers.Buffer_Access_Cursor; end record; end Babel.Streams.Cached;
----------------------------------------------------------------------- -- babel-streams-cached -- Cached stream management -- 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. ----------------------------------------------------------------------- -- == Cached Stream == -- The <tt>Babel.Streams.Cached</tt> package provides a cached stream where the whole -- stream is read in one or several stream buffers. package Babel.Streams.Cached is type Stream_Type is new Babel.Streams.Stream_Type with private; type Stream_Access is access all Stream_Type'Class; -- Load the file stream into the cache and use the buffer pool to obtain more buffers -- for the cache. procedure Load (Stream : in out Stream_Type; File : in out Babel.Streams.Stream_Type'Class; Pool : in out Babel.Files.Buffers.Buffer_Pool); -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. overriding procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access); -- Write the buffer in the data stream. overriding procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access); -- Prepare to read again the data stream from the beginning. overriding procedure Rewind (Stream : in out Stream_Type); private type Stream_Type is new Babel.Streams.Stream_Type with record Input : Babel.Streams.Stream_Access; Output : Babel.Streams.Stream_Access; Buffers : Babel.Files.Buffers.Buffer_Access_Vector; Current : Babel.Files.Buffers.Buffer_Access_Cursor; end record; -- Release the buffers associated with the cache. overriding procedure Finalize (Stream : in out Stream_Type); end Babel.Streams.Cached;
Define the Load and Finish procedures
Define the Load and Finish procedures
Ada
apache-2.0
stcarrez/babel
0c461aa77fde5a379d7387bff82109aa0fa81da2
src/el-expressions-nodes.ads
src/el-expressions-nodes.ads
----------------------------------------------------------------------- -- EL.Expressions -- Expression Nodes -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. function Get_Value (Expr : ELNode; Context : ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : ELNode; Context : ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELUnary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELBinary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELTernary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELVariable; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELValue; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELObject; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELFunction; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : Unbounded_String) return ELNode_Access; function Create_Value (Variable : ELNode_Access; Name : Unbounded_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELValue is new ELNode with record Name : Unbounded_String; Variable : ELNode_Access; end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
----------------------------------------------------------------------- -- EL.Expressions -- Expression Nodes -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. function Get_Value (Expr : ELNode; Context : ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : ELNode; Context : ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELUnary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELBinary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELTernary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELVariable; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELValue; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELObject; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELFunction; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : Unbounded_String) return ELNode_Access; function Create_Value (Variable : ELNode_Access; Name : Unbounded_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELValue is new ELNode with record Name : Unbounded_String; Variable : ELNode_Access; end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
Fix indentation
Fix indentation
Ada
apache-2.0
stcarrez/ada-el
59209fabfc5b10eb7dd12b4228b100212d19723e
tools/druss-commands-get.adb
tools/druss-commands-get.adb
----------------------------------------------------------------------- -- druss-commands-get -- Raw JSON API Get command -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Containers; with Bbox.API; with Druss.Gateways; package body Druss.Commands.Get is use type Ada.Containers.Count_Type; use Ada.Text_IO; use Ada.Strings.Unbounded; -- ------------------------------ -- Execute a GET operation on the Bbox API and return the raw JSON result. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); procedure Execute_One (Gateway : in out Druss.Gateways.Gateway_Type); Need_Colon : Boolean := False; -- Execute the GET API operation and print the raw JSON result. procedure Execute_One (Gateway : in out Druss.Gateways.Gateway_Type) is Box : Bbox.API.Client_Type; begin Box.Set_Server (To_String (Gateway.Ip)); if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then Box.Login (To_String (Gateway.Passwd)); end if; for I in 1 .. Args.Get_Count loop declare Operation : constant String := Args.Get_Argument (I); Content : constant String := Box.Get (Operation); Last : Natural := Content'Last; begin if Need_Colon then Ada.Text_IO.Put (","); end if; while Last > Content'First and Content (Last) = ASCII.LF loop Last := Last - 1; end loop; -- We did a mistake when we designed the Bbox API and used '[' ... ']' arrays -- for most of the JSON result. Strip that unecessary array. if Content (Content'First) = '[' and Content (Last) = ']' then Ada.Text_IO.Put_Line (Content (Content'First + 1 .. Last - 1)); else Ada.Text_IO.Put_Line (Box.Get (Operation)); end if; Need_Colon := True; end; end loop; end Execute_One; begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); else if Args.Get_Count > 1 or else Context.Gateways.Length > 1 then Ada.Text_IO.Put_Line ("["); end if; Druss.Gateways.Iterate (Context.Gateways, Execute_One'Access); if Args.Get_Count > 1 or else Context.Gateways.Length > 1 then Ada.Text_IO.Put_Line ("]"); end if; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin Put_Line ("get: Execute one or several GET operation on the Bbox API" & " and print the raw JSON result"); Put_Line ("Usage: get <operation>..."); New_Line; Put_Line (" The Bbox API operation are called and the raw JSON result is printed."); Put_Line (" When several operations are called, a JSON array is formed to insert"); Put_Line (" their result in the final JSON content so that it is valid."); Put_Line (" Examples:"); Put_Line (" get device Get information about the Bbox"); Put_Line (" get hosts Get the list of hosts detected by the Bbox"); Put_Line (" get wan/ip Get information about the WAN connection"); Put_Line (" get wan/ip wan/xdsl Get the WAN connection and xDSL line information"); end Help; end Druss.Commands.Get;
----------------------------------------------------------------------- -- druss-commands-get -- Raw JSON API Get command -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Unbounded; with Ada.Containers; with Bbox.API; with Druss.Gateways; package body Druss.Commands.Get is use type Ada.Containers.Count_Type; use Ada.Text_IO; use Ada.Strings.Unbounded; -- ------------------------------ -- Execute a GET operation on the Bbox API and return the raw JSON result. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); procedure Execute_One (Gateway : in out Druss.Gateways.Gateway_Type); Need_Colon : Boolean := False; -- Execute the GET API operation and print the raw JSON result. procedure Execute_One (Gateway : in out Druss.Gateways.Gateway_Type) is Box : Bbox.API.Client_Type; begin Box.Set_Server (To_String (Gateway.Ip)); if Ada.Strings.Unbounded.Length (Gateway.Passwd) > 0 then Box.Login (To_String (Gateway.Passwd)); end if; for I in 1 .. Args.Get_Count loop declare Operation : constant String := Args.Get_Argument (I); Content : constant String := Box.Get (Operation); Last : Natural := Content'Last; begin if Need_Colon then Ada.Text_IO.Put (","); end if; while Last > Content'First and Content (Last) = ASCII.LF loop Last := Last - 1; end loop; -- We did a mistake when we designed the Bbox API and used '[' ... ']' arrays -- for most of the JSON result. Strip that unecessary array. if Content (Content'First) = '[' and Content (Last) = ']' then Ada.Text_IO.Put_Line (Content (Content'First + 1 .. Last - 1)); else Ada.Text_IO.Put_Line (Box.Get (Operation)); end if; Need_Colon := True; end; end loop; end Execute_One; begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); else if Args.Get_Count > 1 or else Context.Gateways.Length > 1 then Ada.Text_IO.Put_Line ("["); end if; Druss.Gateways.Iterate (Context.Gateways, Execute_One'Access); if Args.Get_Count > 1 or else Context.Gateways.Length > 1 then Ada.Text_IO.Put_Line ("]"); end if; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Context); begin Put_Line ("get: Execute one or several GET operation on the Bbox API" & " and print the raw JSON result"); Put_Line ("Usage: get <operation>..."); New_Line; Put_Line (" The Bbox API operation are called and the raw JSON result is printed."); Put_Line (" When several operations are called, a JSON array is formed to insert"); Put_Line (" their result in the final JSON content so that it is valid."); Put_Line (" Examples:"); Put_Line (" get device Get information about the Bbox"); Put_Line (" get hosts Get the list of hosts detected by the Bbox"); Put_Line (" get wan/ip Get information about the WAN connection"); Put_Line (" get wan/ip wan/xdsl Get the WAN connection and xDSL line information"); end Help; end Druss.Commands.Get;
Add with clause Ada.Strings.Unbounded
Add with clause Ada.Strings.Unbounded
Ada
apache-2.0
stcarrez/bbox-ada-api
e75a1c8326ab205d4d4f2f4453a1bc76a1e45388
src/natools-smaz_generic.adb
src/natools-smaz_generic.adb
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Generic is use type Ada.Streams.Stream_Element_Offset; procedure Find_Entry (Dict : in Dictionary; Template : in String; Code : out Dictionary_Code; Length : out Natural); -- Try to find the longest entry in Dict that is a prefix of Template, -- setting Length to 0 when no such entry exists. function Verbatim_Size (Dict : in Dictionary; Length : in Positive) return Ada.Streams.Stream_Element_Count is (Verbatim_Size (Length, Dict.Last_Code, Dict.Variable_Length_Verbatim)); -- Wrapper around the formal Verbatim_Size ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Find_Entry (Dict : in Dictionary; Template : in String; Code : out Dictionary_Code; Length : out Natural) is N : Natural; Is_Valid : Boolean; begin Length := 0; for Last in reverse Template'Range loop Is_Valid := False; N := Dict.Hash (Template (Template'First .. Last)); To_Code : begin Code := Dictionary_Code'Val (N); if Is_Valid_Code (Dict, Code) then Is_Valid := True; end if; exception when Constraint_Error => null; end To_Code; if Is_Valid and then Dict_Entry (Dict, Code) = Template (Template'First .. Last) then Length := 1 + Last - Template'First; return; end if; end loop; end Find_Entry; ---------------------- -- Public Interface -- ---------------------- function Compressed_Upper_Bound (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Count is begin return Verbatim_Size (Input'Length, Dict.Last_Code, Dict.Variable_Length_Verbatim); end Compressed_Upper_Bound; procedure Compress (Dict : in Dictionary; Input : in String; Output_Buffer : out Ada.Streams.Stream_Element_Array; Output_Last : out Ada.Streams.Stream_Element_Offset) is procedure Find_Current_Entry; Input_Index : Positive := Input'First; Length : Natural; Code : Dictionary_Code; Output_Index : Ada.Streams.Stream_Element_Offset; procedure Find_Current_Entry is begin Find_Entry (Dict, Input (Input_Index .. Natural'Min (Input_Index + Dict.Max_Word_Length - 1, Input'Last)), Code, Length); end Find_Current_Entry; Previous_Verbatim_Beginning : Natural := 0; Previous_Verbatim_Index : Ada.Streams.Stream_Element_Offset := 0; begin Output_Index := Output_Buffer'First; Find_Current_Entry; Main_Loop : while Input_Index in Input'Range loop Data_In_Dict : while Length > 0 loop Write_Code (Output_Buffer, Output_Index, Code); Input_Index := Input_Index + Length; exit Main_Loop when Input_Index not in Input'Range; Find_Current_Entry; end loop Data_In_Dict; Verbatim_Block : declare Beginning : Positive := Input_Index; Verbatim_Length : Natural; begin Verbatim_Scan : while Length = 0 and Input_Index in Input'Range loop Input_Index := Input_Index + 1; Find_Current_Entry; end loop Verbatim_Scan; Verbatim_Length := Input_Index - Beginning; if Previous_Verbatim_Beginning > 0 and then Output_Index + Verbatim_Size (Dict, Verbatim_Length) >= Previous_Verbatim_Index + Verbatim_Size (Dict, Input_Index - Previous_Verbatim_Beginning) then Beginning := Previous_Verbatim_Beginning; Output_Index := Previous_Verbatim_Index; Verbatim_Length := Input_Index - Beginning; else Previous_Verbatim_Beginning := Beginning; Previous_Verbatim_Index := Output_Index; end if; Write_Verbatim (Output_Buffer, Output_Index, Input (Beginning .. Input_Index - 1), Dict.Last_Code, Dict.Variable_Length_Verbatim); end Verbatim_Block; end loop Main_Loop; Output_Last := Output_Index - 1; end Compress; function Compress (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Array is Result : Ada.Streams.Stream_Element_Array (1 .. Compressed_Upper_Bound (Dict, Input)); Last : Ada.Streams.Stream_Element_Offset; begin Compress (Dict, Input, Result, Last); return Result (Result'First .. Last); end Compress; function Decompressed_Length (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return Natural is Result : Natural := 0; Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Code : Dictionary_Code; Verbatim_Length : Natural; begin while Input_Index in Input'Range loop Read_Code (Input, Input_Index, Code, Verbatim_Length, Dict.Last_Code, Dict.Variable_Length_Verbatim); if Verbatim_Length > 0 then Skip_Verbatim (Input, Input_Index, Verbatim_Length); Result := Result + Verbatim_Length; else Result := Result + Dict_Entry_Length (Dict, Code); end if; end loop; return Result; end Decompressed_Length; procedure Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array; Output_Buffer : out String; Output_Last : out Natural) is Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Code : Dictionary_Code; Verbatim_Length : Natural; begin Output_Last := Output_Buffer'First - 1; while Input_Index in Input'Range loop Read_Code (Input, Input_Index, Code, Verbatim_Length, Dict.Last_Code, Dict.Variable_Length_Verbatim); if Verbatim_Length > 0 then Read_Verbatim (Input, Input_Index, Output_Buffer (Output_Last + 1 .. Output_Last + Verbatim_Length)); Output_Last := Output_Last + Verbatim_Length; else declare Decoded : constant String := Dict_Entry (Dict, Code); begin Output_Buffer (Output_Last + 1 .. Output_Last + Decoded'Length) := Decoded; Output_Last := Output_Last + Decoded'Length; end; end if; end loop; end Decompress; function Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return String is Result : String (1 .. Decompressed_Length (Dict, Input)); Last : Natural; begin Decompress (Dict, Input, Result, Last); pragma Assert (Last = Result'Last); return Result; end Decompress; end Natools.Smaz_Generic;
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Generic is use type Ada.Streams.Stream_Element_Offset; procedure Find_Entry (Dict : in Dictionary; Template : in String; Code : out Dictionary_Code; Length : out Natural); -- Try to find the longest entry in Dict that is a prefix of Template, -- setting Length to 0 when no such entry exists. function Verbatim_Size (Dict : in Dictionary; Length : in Positive) return Ada.Streams.Stream_Element_Count is (Verbatim_Size (Length, Dict.Last_Code, Dict.Variable_Length_Verbatim)); -- Wrapper around the formal Verbatim_Size ------------------------------ -- Local Helper Subprograms -- ------------------------------ procedure Find_Entry (Dict : in Dictionary; Template : in String; Code : out Dictionary_Code; Length : out Natural) is N : Natural; Is_Valid : Boolean; begin Length := 0; for Last in reverse Template'Range loop Is_Valid := False; N := Dict.Hash (Template (Template'First .. Last)); To_Code : begin Code := Dictionary_Code'Val (N); if Is_Valid_Code (Dict, Code) then Is_Valid := True; end if; exception when Constraint_Error => null; end To_Code; if Is_Valid and then Template (Template'First .. Last) = Dict.Values (Code_First (Dict.Offsets, Code, Dict.Values'First) .. Code_Last (Dict.Offsets, Code, Dict.Values'Last)) then Length := 1 + Last - Template'First; return; end if; end loop; end Find_Entry; ---------------------- -- Public Interface -- ---------------------- function Compressed_Upper_Bound (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Count is begin return Verbatim_Size (Input'Length, Dict.Last_Code, Dict.Variable_Length_Verbatim); end Compressed_Upper_Bound; procedure Compress (Dict : in Dictionary; Input : in String; Output_Buffer : out Ada.Streams.Stream_Element_Array; Output_Last : out Ada.Streams.Stream_Element_Offset) is procedure Find_Current_Entry; Input_Index : Positive := Input'First; Length : Natural; Code : Dictionary_Code; Output_Index : Ada.Streams.Stream_Element_Offset; procedure Find_Current_Entry is begin Find_Entry (Dict, Input (Input_Index .. Natural'Min (Input_Index + Dict.Max_Word_Length - 1, Input'Last)), Code, Length); end Find_Current_Entry; Previous_Verbatim_Beginning : Natural := 0; Previous_Verbatim_Index : Ada.Streams.Stream_Element_Offset := 0; begin Output_Index := Output_Buffer'First; Find_Current_Entry; Main_Loop : while Input_Index in Input'Range loop Data_In_Dict : while Length > 0 loop Write_Code (Output_Buffer, Output_Index, Code); Input_Index := Input_Index + Length; exit Main_Loop when Input_Index not in Input'Range; Find_Current_Entry; end loop Data_In_Dict; Verbatim_Block : declare Beginning : Positive := Input_Index; Verbatim_Length : Natural; begin Verbatim_Scan : while Length = 0 and Input_Index in Input'Range loop Input_Index := Input_Index + 1; Find_Current_Entry; end loop Verbatim_Scan; Verbatim_Length := Input_Index - Beginning; if Previous_Verbatim_Beginning > 0 and then Output_Index + Verbatim_Size (Dict, Verbatim_Length) >= Previous_Verbatim_Index + Verbatim_Size (Dict, Input_Index - Previous_Verbatim_Beginning) then Beginning := Previous_Verbatim_Beginning; Output_Index := Previous_Verbatim_Index; Verbatim_Length := Input_Index - Beginning; else Previous_Verbatim_Beginning := Beginning; Previous_Verbatim_Index := Output_Index; end if; Write_Verbatim (Output_Buffer, Output_Index, Input (Beginning .. Input_Index - 1), Dict.Last_Code, Dict.Variable_Length_Verbatim); end Verbatim_Block; end loop Main_Loop; Output_Last := Output_Index - 1; end Compress; function Compress (Dict : in Dictionary; Input : in String) return Ada.Streams.Stream_Element_Array is Result : Ada.Streams.Stream_Element_Array (1 .. Compressed_Upper_Bound (Dict, Input)); Last : Ada.Streams.Stream_Element_Offset; begin Compress (Dict, Input, Result, Last); return Result (Result'First .. Last); end Compress; function Decompressed_Length (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return Natural is Result : Natural := 0; Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Code : Dictionary_Code; Verbatim_Length : Natural; begin while Input_Index in Input'Range loop Read_Code (Input, Input_Index, Code, Verbatim_Length, Dict.Last_Code, Dict.Variable_Length_Verbatim); if Verbatim_Length > 0 then Skip_Verbatim (Input, Input_Index, Verbatim_Length); Result := Result + Verbatim_Length; else Result := Result + Dict_Entry_Length (Dict, Code); end if; end loop; return Result; end Decompressed_Length; procedure Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array; Output_Buffer : out String; Output_Last : out Natural) is Input_Index : Ada.Streams.Stream_Element_Offset := Input'First; Code : Dictionary_Code; Verbatim_Length : Natural; begin Output_Last := Output_Buffer'First - 1; while Input_Index in Input'Range loop Read_Code (Input, Input_Index, Code, Verbatim_Length, Dict.Last_Code, Dict.Variable_Length_Verbatim); if Verbatim_Length > 0 then Read_Verbatim (Input, Input_Index, Output_Buffer (Output_Last + 1 .. Output_Last + Verbatim_Length)); Output_Last := Output_Last + Verbatim_Length; else declare Decoded : constant String := Dict_Entry (Dict, Code); begin Output_Buffer (Output_Last + 1 .. Output_Last + Decoded'Length) := Decoded; Output_Last := Output_Last + Decoded'Length; end; end if; end loop; end Decompress; function Decompress (Dict : in Dictionary; Input : in Ada.Streams.Stream_Element_Array) return String is Result : String (1 .. Decompressed_Length (Dict, Input)); Last : Natural; begin Decompress (Dict, Input, Result, Last); pragma Assert (Last = Result'Last); return Result; end Decompress; end Natools.Smaz_Generic;
optimize compression
smaz_generic: optimize compression For some reason it seems even with -O3, calling Dict_Entry involves a string copy, which makes `memcpy` the larger time consumer of the copmpression algorithm. Inlining it manually improves performance a lot.
Ada
isc
faelys/natools
434b6a56a0d85b9428dd99c98df47310cdd3cdef
src/security-contexts.adb
src/security-contexts.adb
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Security.Controllers; package body Security.Contexts is package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean) is use type Security.Policies.Controller_Access; use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare C : constant Policies.Controller_Access := Context.Manager.Get_Controller (Permission); begin if C = null then Result := False; else -- Result := C.Has_Permission (Context); Result := False; end if; end; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean) is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin Security_Context'Class (Context).Has_Permission (Index, Result); end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is begin Task_Context.Set_Value (Context.Previous); end Finalize; -- ------------------------------ -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. -- ------------------------------ procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String) is begin Context.Context.Include (Key => Name, New_Item => Value); end Add_Context; -- ------------------------------ -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- ------------------------------ function Get_Context (Context : in Security_Context; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else raise Invalid_Context; end if; end Get_Context; -- ------------------------------ -- Returns True if a context information was registered under the name <b>Name</b>. -- ------------------------------ function Has_Context (Context : in Security_Context; Name : in String) return Boolean is use type Util.Strings.Maps.Cursor; begin return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element; end Has_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in String) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; end Security.Contexts;
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; package body Security.Contexts is package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean) is use type Security.Policies.Controller_Access; use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare C : constant Policies.Controller_Access := Context.Manager.Get_Controller (Permission); begin if C = null then Result := False; else -- Result := C.Has_Permission (Context); Result := False; end if; end; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean) is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin Security_Context'Class (Context).Has_Permission (Index, Result); end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is begin Task_Context.Set_Value (Context.Previous); end Finalize; -- ------------------------------ -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. -- ------------------------------ procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String) is begin Context.Context.Include (Key => Name, New_Item => Value); end Add_Context; -- ------------------------------ -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- ------------------------------ function Get_Context (Context : in Security_Context; Name : in String) return String is Pos : constant Util.Strings.Maps.Cursor := Context.Context.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Util.Strings.Maps.Element (Pos); else raise Invalid_Context; end if; end Get_Context; -- ------------------------------ -- Returns True if a context information was registered under the name <b>Name</b>. -- ------------------------------ function Has_Context (Context : in Security_Context; Name : in String) return Boolean is use type Util.Strings.Maps.Cursor; begin return Context.Context.Find (Name) /= Util.Strings.Maps.No_Element; end Has_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in String) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; end Security.Contexts;
Remove unused with clause
Remove unused with clause
Ada
apache-2.0
stcarrez/ada-security
1289f19a0764043f199c18800ccde7e1a3832082
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 Util.Strings.Maps; with Security.Permissions; -- == 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; 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.Permissions.Permission_Manager_Access; pragma Inline_Always (Get_Permission_Manager); -- 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); -- 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.Permissions.Permission_Manager_Access; Principal : in Security.Principal_Access); -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String); -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. function Get_Context (Context : in Security_Context; Name : in String) return String; -- Returns True if a context information was registered under the name <b>Name</b>. function Has_Context (Context : in Security_Context; Name : in String) 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.Permissions.Permission_Manager_Access := null; Principal : Security.Principal_Access := null; Context : Util.Strings.Maps.Map; 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 Util.Strings.Maps; 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; 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); -- 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); -- 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); -- Add a context information represented by <b>Value</b> under the name identified by -- <b>Name</b> in the security context <b>Context</b>. procedure Add_Context (Context : in out Security_Context; Name : in String; Value : in String); -- Get the context information registered under the name <b>Name</b> in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. function Get_Context (Context : in Security_Context; Name : in String) return String; -- Returns True if a context information was registered under the name <b>Name</b>. function Has_Context (Context : in Security_Context; Name : in String) 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; Context : Util.Strings.Maps.Map; end record; end Security.Contexts;
Use the Policy manager
Use the Policy manager
Ada
apache-2.0
stcarrez/ada-security
43c8b0b48e81ec1889c658b986d18472fde83efa
src/wiki-parsers-html.adb
src/wiki-parsers-html.adb
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wiki.Strings.WChar; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := False; end if; else End_Element (P, Tag); end if; else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := True; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline_Always (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline_Always (Add_Element); Name : Wiki.Strings.BString (64); begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Add_Element (Name); end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
----------------------------------------------------------------------- -- wiki-parsers-html -- Wiki HTML parser -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; with Wiki.Parsers.Html.Entities; package body Wiki.Parsers.Html is -- Parse an HTML attribute procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString); -- Parse a HTML/XML comment to strip it. procedure Parse_Comment (P : in out Parser); -- Parse a simple DOCTYPE declaration and ignore it. procedure Parse_Doctype (P : in out Parser); procedure Collect_Attributes (P : in out Parser); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString); function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is begin return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"' and C /= '/' and C /= '=' and C /= '<'; end Is_Letter; -- ------------------------------ -- Parse an HTML attribute -- ------------------------------ procedure Parse_Attribute_Name (P : in out Parser; Name : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; begin Skip_Spaces (P); while not P.Is_Eof loop Peek (P, C); if not Is_Letter (C) then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Name, C); end loop; end Parse_Attribute_Name; procedure Collect_Attribute_Value (P : in out Parser; Value : in out Wiki.Strings.BString) is C : Wiki.Strings.WChar; Token : Wiki.Strings.WChar; begin -- Value := Wiki.Strings.To_UString (""); Peek (P, Token); if Wiki.Helpers.Is_Space (Token) then return; elsif Token = '>' then Put_Back (P, Token); return; elsif Token /= ''' and Token /= '"' then Wiki.Strings.Wide_Wide_Builders.Append (Value, Token); while not P.Is_Eof loop Peek (P, C); if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then Put_Back (P, C); return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; else while not P.Is_Eof loop Peek (P, C); if C = Token then return; end if; Wiki.Strings.Wide_Wide_Builders.Append (Value, C); end loop; end if; end Collect_Attribute_Value; -- ------------------------------ -- Parse a list of HTML attributes up to the first '>'. -- attr-name -- attr-name= -- attr-name=value -- attr-name='value' -- attr-name="value" -- <name name='value' ...> -- ------------------------------ procedure Collect_Attributes (P : in out Parser) is procedure Append_Attribute (Name : in Wiki.Strings.WString); C : Wiki.Strings.WChar; Name : Wiki.Strings.BString (64); Value : Wiki.Strings.BString (256); procedure Append_Attribute (Name : in Wiki.Strings.WString) is procedure Attribute_Value (Value : in Wiki.Strings.WString); procedure Attribute_Value (Value : in Wiki.Strings.WString) is begin Attributes.Append (P.Attributes, Name, Value); end Attribute_Value; procedure Attribute_Value is new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value); pragma Inline (Attribute_Value); begin Attribute_Value (Value); end Append_Attribute; pragma Inline (Append_Attribute); procedure Append_Attribute is new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute); begin Wiki.Attributes.Clear (P.Attributes); while not P.Is_Eof loop Parse_Attribute_Name (P, Name); Skip_Spaces (P); Peek (P, C); if C = '>' or C = '<' or C = '/' then Put_Back (P, C); exit; end if; if C = '=' then Collect_Attribute_Value (P, Value); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Value); elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Put_Back (P, C); Append_Attribute (Name); Wiki.Strings.Wide_Wide_Builders.Clear (Name); end if; end loop; -- Add any pending attribute. if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then Append_Attribute (Name); end if; end Collect_Attributes; -- ------------------------------ -- Parse a HTML/XML comment to strip it. -- ------------------------------ procedure Parse_Comment (P : in out Parser) is C : Wiki.Strings.WChar; begin Peek (P, C); while not P.Is_Eof loop Peek (P, C); if C = '-' then declare Count : Natural := 1; begin Peek (P, C); while not P.Is_Eof and C = '-' loop Peek (P, C); Count := Count + 1; end loop; exit when C = '>' and Count >= 2; end; end if; end loop; end Parse_Comment; -- ------------------------------ -- Parse a simple DOCTYPE declaration and ignore it. -- ------------------------------ procedure Parse_Doctype (P : in out Parser) is C : Wiki.Strings.WChar; begin while not P.Is_Eof loop Peek (P, C); exit when C = '>'; end loop; end Parse_Doctype; -- ------------------------------ -- Parse a HTML element <XXX attributes> -- or parse an end of HTML element </XXX> -- ------------------------------ procedure Parse_Element (P : in out Parser) is C : Wiki.Strings.WChar; procedure Add_Element (Token : in Wiki.Strings.WString); procedure Add_Element (Token : in Wiki.Strings.WString) is Tag : Wiki.Html_Tag; begin Tag := Wiki.Find_Tag (Token); if C = '/' then Skip_Spaces (P); Peek (P, C); if C /= '>' then Put_Back (P, C); end if; Flush_Text (P); if Tag = Wiki.UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := False; end if; else End_Element (P, Tag); end if; else Collect_Attributes (P); Peek (P, C); if C = '/' then Peek (P, C); if C = '>' then Start_Element (P, Tag, P.Attributes); End_Element (P, Tag); return; end if; elsif C /= '>' then Put_Back (P, C); end if; if Tag = UNKNOWN_TAG then if Token = "noinclude" then P.Is_Hidden := True; end if; else Start_Element (P, Tag, P.Attributes); end if; end if; end Add_Element; pragma Inline (Add_Element); procedure Add_Element is new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element); pragma Inline (Add_Element); Name : Wiki.Strings.BString (64); begin Peek (P, C); if C = '!' then Peek (P, C); if C = '-' then Parse_Comment (P); else Parse_Doctype (P); end if; return; end if; if C /= '/' then Put_Back (P, C); end if; Parse_Attribute_Name (P, Name); Add_Element (Name); end Parse_Element; -- ------------------------------ -- Parse an HTML entity such as &nbsp; and replace it with the corresponding code. -- ------------------------------ procedure Parse_Entity (P : in out Parser; Token : in Wiki.Strings.WChar) is pragma Unreferenced (Token); Name : String (1 .. 10); Len : Natural := 0; High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last; Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First; Pos : Natural; C : Wiki.Strings.WChar; begin while Len < Name'Last loop Peek (P, C); exit when C = ';' or else P.Is_Eof; Len := Len + 1; Name (Len) := Wiki.Strings.To_Char (C); end loop; while Low <= High loop Pos := (Low + High) / 2; if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then Parse_Text (P, Entities.Mapping (Pos)); return; elsif Entities.Keywords (Pos).all < Name (1 .. Len) then Low := Pos + 1; else High := Pos - 1; end if; end loop; -- The HTML entity is not recognized: we must treat it as plain wiki text. Parse_Text (P, '&'); for I in 1 .. Len loop Parse_Text (P, Wiki.Strings.To_WChar (Name (I))); end loop; end Parse_Entity; end Wiki.Parsers.Html;
Change pragma Inline_Always to Inline for old compiler
Change pragma Inline_Always to Inline for old compiler
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
93318d43747216efdedb94adc8232ce57683e7f4
mat/src/events/mat-events-targets.adb
mat/src/events/mat-events-targets.adb
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while not Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id; if Pos < Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; end Event_Collector; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Events.Targets is -- ------------------------------ -- Add the event in the list of events and increment the event counter. -- ------------------------------ procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type) is begin Target.Events.Insert (Event); Util.Concurrent.Counters.Increment (Target.Event_Count); end Insert; procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is begin Target.Events.Get_Events (Start, Finish, Into); end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is begin Target.Events.Get_Time_Range (Start, Finish); end Get_Time_Range; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type is begin return Target.Events.Get_Event (Id); end Get_Event; -- ------------------------------ -- Get the current event counter. -- ------------------------------ function Get_Event_Counter (Target : in Target_Events) return Integer is begin return Util.Concurrent.Counters.Value (Target.Event_Count); end Get_Event_Counter; protected body Event_Collector is -- ------------------------------ -- Add the event in the list of events. -- ------------------------------ procedure Insert (Event : in Probe_Event_Type) is Info : Target_Event; begin if Current = null then Current := new Event_Block; Current.Start := Event.Time; Events.Insert (Event.Time, Current); Ids.Insert (Last_Id + 1, Current); end if; Current.Count := Current.Count + 1; Current.Events (Current.Count) := Event; Current.Events (Current.Count).Id := Last_Id; Last_Id := Last_Id + 1; Current.Finish := Event.Time; if Current.Count = Current.Events'Last then Current := null; end if; end Insert; procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector) is Iter : Event_Cursor := Events.Floor (Start); Block : Event_Block_Access; begin while Event_Maps.Has_Element (Iter) loop Block := Event_Maps.Element (Iter); exit when Block.Start > Finish; for I in Block.Events'First .. Block.Count loop exit when Block.Events (I).Time > Finish; if Block.Events (I).Time >= Start then Into.Append (Block.Events (I)); end if; end loop; Event_Maps.Next (Iter); end loop; end Get_Events; -- ------------------------------ -- Get the start and finish time for the events that have been received. -- ------------------------------ procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time) is First : constant Event_Block_Access := Events.First_Element; Last : constant Event_Block_Access := Events.Last_Element; begin Start := First.Events (First.Events'First).Time; Finish := Last.Events (Last.Count).Time; end Get_Time_Range; -- ------------------------------ -- Get the probe event with the given allocated unique id. -- ------------------------------ function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is Iter : Event_Id_Cursor := Ids.Floor (Id); Block : Event_Block_Access; Pos : Event_Id_Type; begin while Event_Id_Maps.Has_Element (Iter) loop Block := Event_Id_Maps.Element (Iter); exit when Id < Block.Events (Block.Events'First).Id; Pos := Id - Block.Events (Block.Events'First).Id; if Pos < Block.Count then return Block.Events (Pos); end if; Event_Id_Maps.Next (Iter); end loop; raise Not_Found; end Get_Event; end Event_Collector; end MAT.Events.Targets;
Fix the Get_Event procedure
Fix the Get_Event procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
21f82397c418c064056bbe9a13f43e47129653ff
awa/plugins/awa-questions/regtests/awa-questions-services-tests.ads
awa/plugins/awa-questions/regtests/awa-questions-services-tests.ads
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for question 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.Questions.Services.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Questions.Services.Question_Service_Access; end record; -- Test creation of a question. procedure Test_Create_Question (T : in out Test); -- Test list of questions. procedure Test_List_Questions (T : in out Test); end AWA.Questions.Services.Tests;
----------------------------------------------------------------------- -- awa-questions-services-tests -- Unit tests for question 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.Questions.Services.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Manager : AWA.Questions.Services.Question_Service_Access; end record; -- Test creation of a question. procedure Test_Create_Question (T : in out Test); -- Test list of questions. procedure Test_List_Questions (T : in out Test); -- Test anonymous user voting for a question. procedure Test_Question_Vote_Anonymous (T : in out Test); -- Test voting for a question. procedure Test_Question_Vote (T : in out Test); private -- Do a vote on a question through the question vote bean. procedure Do_Vote (T : in out Test); end AWA.Questions.Services.Tests;
Add unit tests for the questionVote bean
Add unit tests for the questionVote bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2b16427c3930e35a2070cce882153de836043365
src/atlas-server.adb
src/atlas-server.adb
----------------------------------------------------------------------- -- atlas-server -- Application server -- Copyright (C) 2011, 2012, 2013, 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.Exceptions; with Util.Log.Loggers; with ADO.Drivers; with AWS.Net.SSL; with AWS.Config.Set; with ASF.Server.Web; with AWA.Setup.Applications; with Atlas.Applications; procedure Atlas.Server is procedure Configure (Config : in out AWS.Config.Object); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; WS : ASF.Server.Web.AWS_Container; procedure Setup is new AWA.Setup.Applications.Configure (Atlas.Applications.Application'Class, Atlas.Applications.Application_Access, Atlas.Applications.Initialize); procedure Configure (Config : in out AWS.Config.Object) is begin AWS.Config.Set.Input_Line_Size_Limit (1_000_000); AWS.Config.Set.Max_Connection (Config, 2); AWS.Config.Set.Accept_Queue_Size (Config, 100); AWS.Config.Set.Send_Buffer_Size (Config, 128 * 1024); AWS.Config.Set.Upload_Size_Limit (Config, 100_000_000); end Configure; begin ADO.Drivers.Initialize; WS.Configure (Configure'Access); WS.Start; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); Setup (WS, App, "atlas", Atlas.Applications.CONTEXT_PATH); if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OAuth2/OpenID connector to " & "connect to OAuth2/OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); end if; delay 365.0 * 24.0 * 3600.0; App.Close; exception when E : others => Log.Error ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Atlas.Server;
----------------------------------------------------------------------- -- atlas-server -- Application server -- Copyright (C) 2011, 2012, 2013, 2016, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with Util.Log.Loggers; with Util.Commands; with ADO.Drivers; with AWS.Net.SSL; with AWS.Config.Set; with Servlet.Server.Web; with AWA.Setup.Applications; with AWA.Commands.Drivers; with AWA.Commands.Start; with AWA.Commands.Setup; with AWA.Commands.Stop; with AWA.Commands.List; with Atlas.Applications; procedure Atlas.Server is package Server_Commands is new AWA.Commands.Drivers (Driver_Name => "atlas", Container_Type => Servlet.Server.Web.AWS_Container); package List_Command is new AWA.Commands.List (Server_Commands); package Start_Command is new AWA.Commands.Start (Server_Commands); package Stop_Command is new AWA.Commands.Stop (Server_Commands); package Setup_Command is new AWA.Commands.Setup (Start_Command); procedure Configure (Config : in out AWS.Config.Object); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server"); App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application; procedure Configure (Config : in out AWS.Config.Object) is begin AWS.Config.Set.Input_Line_Size_Limit (1_000_000); AWS.Config.Set.Max_Connection (Config, 2); AWS.Config.Set.Accept_Queue_Size (Config, 100); AWS.Config.Set.Send_Buffer_Size (Config, 128 * 1024); AWS.Config.Set.Upload_Size_Limit (Config, 100_000_000); end Configure; WS : Servlet.Server.Web.AWS_Container renames Server_Commands.WS; Context : AWA.Commands.Context_Type; Arguments : Util.Commands.Dynamic_Argument_List; begin ADO.Drivers.Initialize; WS.Register_Application (Atlas.Applications.CONTEXT_PATH, App.all'Access); if not AWS.Net.SSL.Is_Supported then Log.Error ("SSL is not supported by AWS."); Log.Error ("SSL is required for the OAuth2/OpenID connector to " & "connect to OAuth2/OpenID providers."); Log.Error ("Please, rebuild AWS with SSL support."); end if; Log.Info ("Connect you browser to: http://localhost:8080{0}/index.html", Atlas.Applications.CONTEXT_PATH); Server_Commands.Run (Context, Arguments); exception when E : others => Log.Error ("Exception in server: " & Ada.Exceptions.Exception_Name (E) & ": " & Ada.Exceptions.Exception_Message (E)); end Atlas.Server;
Update the server to use the AWA.Commands and benefit from various commands (start, stop, setup, list)
Update the server to use the AWA.Commands and benefit from various commands (start, stop, setup, list)
Ada
apache-2.0
stcarrez/atlas
25d441eeffea4b3d1069612a2a30992c7c0924e1
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format; Footer : in Boolean); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_START_CODE, L_END_CODE, L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged null record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; private with Util.Strings.Maps; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_SEE : constant String := "see"; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format; Footer : in Boolean); -- Load from the file a list of link definitions which can be injected in the generated doc. -- This allows to avoid polluting the Ada code with external links. procedure Read_Links (Handler : in out Artifact; Path : in String); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_START_CODE, L_END_CODE, L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4); type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged record Links : Util.Strings.Maps.Map; end record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Vectors.Vector; Was_Included : Boolean := False; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
Declare the Read_Links procedure to read the documentation links file
Declare the Read_Links procedure to read the documentation links file
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
0204485ac9c55e12684cffcaab77efbb197b55b5
test/unit/orka/src/test_transforms_singles_quaternions.adb
test/unit/orka/src/test_transforms_singles_quaternions.adb
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with Ahven; use Ahven; with GL.Types; with Orka.SIMD; with Orka.Transforms.Singles.Quaternions; with Orka.Transforms.Singles.Vectors; package body Test_Transforms_Singles_Quaternions is use GL.Types; use Orka.SIMD; use Orka.Transforms.Singles.Quaternions; package Vectors renames Orka.Transforms.Singles.Vectors; use type Vector4; package EF is new Ada.Numerics.Generic_Elementary_Functions (Single); function Is_Equivalent (Expected, Result : GL.Types.Single) return Boolean is Epsilon : constant GL.Types.Single := 2.0 ** (1 - GL.Types.Single'Model_Mantissa); begin return Result in Expected - Epsilon .. Expected + Epsilon; end Is_Equivalent; overriding procedure Initialize (T : in out Test) is begin T.Set_Name ("Quaternions"); T.Add_Test_Routine (Test_Multiplication'Access, "Test '*' operator"); T.Add_Test_Routine (Test_Conjugate'Access, "Test Conjugate function"); T.Add_Test_Routine (Test_Norm'Access, "Test Norm function"); T.Add_Test_Routine (Test_Normalize'Access, "Test Normalize function"); T.Add_Test_Routine (Test_Normalized'Access, "Test Normalized function"); T.Add_Test_Routine (Test_Rotate_Axis_Angle'Access, "Test Rotate_Axis_Angle function"); T.Add_Test_Routine (Test_Rotate_Vectors'Access, "Test Rotate_Vectors function"); T.Add_Test_Routine (Test_Rotate_At_Origin'Access, "Test Rotate_At_Origin procedure"); T.Add_Test_Routine (Test_Slerp'Access, "Test Slerp function"); end Initialize; procedure Test_Multiplication is Half_Angle : constant GL.Types.Single := 45.0; begin declare Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Sin_Value : constant GL.Types.Single := EF.Sin (Half_Angle, 360.0); Cos_Value : constant GL.Types.Single := EF.Cos (Half_Angle, 360.0); Result : constant Quaternion := R (Axis, Half_Angle) * R (Axis, Half_Angle); Expected : constant Quaternion := (Axis (X) * Sin_Value, Axis (Y) * Sin_Value, Axis (Z) * Sin_Value, Cos_Value); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "A Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; Assert (Normalized (Result), "Result not normalized"); end; declare Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Rotation : constant Quaternion := R (Axis, 30.0) * R (Axis, 30.0) * R (Axis, 30.0); Expected : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Result : Vector4 := (0.0, 1.0, 0.0, 0.0); begin Rotate_At_Origin (Result, Rotation); for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "B Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end; end Test_Multiplication; procedure Test_Conjugate is Elements : constant Quaternion := (1.0, 2.0, 3.0, 4.0); Expected : constant Quaternion := (-1.0, -2.0, -3.0, 4.0); Result : constant Quaternion := Conjugate (Elements); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end Test_Conjugate; procedure Test_Norm is Elements_1 : constant Quaternion := (1.0, 2.0, 3.0, 4.0); Elements_2 : constant Quaternion := (-1.0, 2.0, -3.0, 4.0); Elements_3 : constant Quaternion := (0.0, 0.0, 0.0, 0.0); Result_1 : constant GL.Types.Single := Norm (Elements_1); Result_2 : constant GL.Types.Single := Norm (Elements_2); Result_3 : constant GL.Types.Single := Norm (Elements_3); Expected_1 : constant GL.Types.Single := EF.Sqrt (30.0); Expected_2 : constant GL.Types.Single := EF.Sqrt (30.0); Expected_3 : constant GL.Types.Single := 0.0; begin Assert (Is_Equivalent (Expected_1, Result_1), "Unexpected Single " & GL.Types.Single'Image (Result_1)); Assert (Is_Equivalent (Expected_2, Result_2), "Unexpected Single " & GL.Types.Single'Image (Result_2)); Assert (Is_Equivalent (Expected_3, Result_3), "Unexpected Single " & GL.Types.Single'Image (Result_3)); end Test_Norm; procedure Test_Normalize is Elements : constant Quaternion := (1.0, 2.0, 3.0, 4.0); begin Assert (not Normalized (Elements), "Elements is unexpectedly a unit quaternion"); declare Result : constant Quaternion := Normalize (Elements); begin Assert (Normalized (Result), "Result not normalized"); end; end Test_Normalize; procedure Test_Normalized is Elements_1 : constant Quaternion := (0.0, 0.0, 0.0, 1.0); Elements_2 : constant Quaternion := (0.5, 0.5, 0.5, -0.5); Elements_3 : constant Quaternion := (0.0, -1.0, 0.0, 0.0); Elements_4 : constant Quaternion := (1.0, 2.0, 3.0, 4.0); begin Assert (Normalized (Elements_1), "Elements_1 not normalized"); Assert (Normalized (Elements_2), "Elements_2 not normalized"); Assert (Normalized (Elements_3), "Elements_3 not normalized"); Assert (not Normalized (Elements_4), "Elements_4 normalized"); end Test_Normalized; procedure Test_Rotate_Axis_Angle is Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Angle : constant GL.Types.Single := 90.0; Sin_Value : constant GL.Types.Single := EF.Sin (45.0, 360.0); Cos_Value : constant GL.Types.Single := EF.Cos (45.0, 360.0); Result : constant Quaternion := R (Axis, Angle); Expected : constant Quaternion := (Axis (X) * Sin_Value, Axis (Y) * Sin_Value, Axis (Z) * Sin_Value, Cos_Value); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; Assert (Normalized (Result), "Result not normalized"); end Test_Rotate_Axis_Angle; procedure Test_Rotate_Vectors is Start_Vector : constant Vector4 := (0.0, 1.0, 0.0, 0.0); End_Vector : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant GL.Types.Single := 90.0; Expected : constant Quaternion := R (Axis, Angle); Result : constant Quaternion := R (Start_Vector, End_Vector); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end Test_Rotate_Vectors; procedure Test_Rotate_At_Origin is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant GL.Types.Single := 90.0; Rotation : constant Quaternion := R (Axis, Angle); Expected : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Result : Vector4 := (0.0, 1.0, 0.0, 0.0); begin Rotate_At_Origin (Result, Rotation); for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end Test_Rotate_At_Origin; procedure Test_Slerp is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant GL.Types.Single := 45.0; Start_Quaternion : constant Quaternion := R (Axis, 0.0); End_Quaternion : constant Quaternion := R (Axis, 90.0); Expected : constant Quaternion := R (Axis, Angle); Result : constant Quaternion := Slerp (Start_Quaternion, End_Quaternion, 0.5); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end Test_Slerp; end Test_Transforms_Singles_Quaternions;
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Numerics.Generic_Elementary_Functions; with Ahven; use Ahven; with GL.Types; with Orka.SIMD; with Orka.Transforms.Singles.Quaternions; with Orka.Transforms.Singles.Vectors; package body Test_Transforms_Singles_Quaternions is use GL.Types; use Orka.SIMD; use Orka.Transforms.Singles.Quaternions; package Vectors renames Orka.Transforms.Singles.Vectors; use type Vector4; package EF is new Ada.Numerics.Generic_Elementary_Functions (Single); function Is_Equivalent (Expected, Result : GL.Types.Single) return Boolean is Epsilon : constant GL.Types.Single := GL.Types.Single'Model_Epsilon; begin return Result in Expected - Epsilon .. Expected + Epsilon; end Is_Equivalent; overriding procedure Initialize (T : in out Test) is begin T.Set_Name ("Quaternions"); T.Add_Test_Routine (Test_Multiplication'Access, "Test '*' operator"); T.Add_Test_Routine (Test_Conjugate'Access, "Test Conjugate function"); T.Add_Test_Routine (Test_Norm'Access, "Test Norm function"); T.Add_Test_Routine (Test_Normalize'Access, "Test Normalize function"); T.Add_Test_Routine (Test_Normalized'Access, "Test Normalized function"); T.Add_Test_Routine (Test_Rotate_Axis_Angle'Access, "Test Rotate_Axis_Angle function"); T.Add_Test_Routine (Test_Rotate_Vectors'Access, "Test Rotate_Vectors function"); T.Add_Test_Routine (Test_Rotate_At_Origin'Access, "Test Rotate_At_Origin procedure"); T.Add_Test_Routine (Test_Slerp'Access, "Test Slerp function"); end Initialize; procedure Test_Multiplication is Half_Angle : constant GL.Types.Single := 45.0; begin declare Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Sin_Value : constant GL.Types.Single := EF.Sin (Half_Angle, 360.0); Cos_Value : constant GL.Types.Single := EF.Cos (Half_Angle, 360.0); Result : constant Quaternion := R (Axis, Half_Angle) * R (Axis, Half_Angle); Expected : constant Quaternion := (Axis (X) * Sin_Value, Axis (Y) * Sin_Value, Axis (Z) * Sin_Value, Cos_Value); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "A Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; Assert (Normalized (Result), "Result not normalized"); end; declare Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Rotation : constant Quaternion := R (Axis, 30.0) * R (Axis, 30.0) * R (Axis, 30.0); Expected : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Result : Vector4 := (0.0, 1.0, 0.0, 0.0); begin Rotate_At_Origin (Result, Rotation); for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "B Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end; end Test_Multiplication; procedure Test_Conjugate is Elements : constant Quaternion := (1.0, 2.0, 3.0, 4.0); Expected : constant Quaternion := (-1.0, -2.0, -3.0, 4.0); Result : constant Quaternion := Conjugate (Elements); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end Test_Conjugate; procedure Test_Norm is Elements_1 : constant Quaternion := (1.0, 2.0, 3.0, 4.0); Elements_2 : constant Quaternion := (-1.0, 2.0, -3.0, 4.0); Elements_3 : constant Quaternion := (0.0, 0.0, 0.0, 0.0); Result_1 : constant GL.Types.Single := Norm (Elements_1); Result_2 : constant GL.Types.Single := Norm (Elements_2); Result_3 : constant GL.Types.Single := Norm (Elements_3); Expected_1 : constant GL.Types.Single := EF.Sqrt (30.0); Expected_2 : constant GL.Types.Single := EF.Sqrt (30.0); Expected_3 : constant GL.Types.Single := 0.0; begin Assert (Is_Equivalent (Expected_1, Result_1), "Unexpected Single " & GL.Types.Single'Image (Result_1)); Assert (Is_Equivalent (Expected_2, Result_2), "Unexpected Single " & GL.Types.Single'Image (Result_2)); Assert (Is_Equivalent (Expected_3, Result_3), "Unexpected Single " & GL.Types.Single'Image (Result_3)); end Test_Norm; procedure Test_Normalize is Elements : constant Quaternion := (1.0, 2.0, 3.0, 4.0); begin Assert (not Normalized (Elements), "Elements is unexpectedly a unit quaternion"); declare Result : constant Quaternion := Normalize (Elements); begin Assert (Normalized (Result), "Result not normalized"); end; end Test_Normalize; procedure Test_Normalized is Elements_1 : constant Quaternion := (0.0, 0.0, 0.0, 1.0); Elements_2 : constant Quaternion := (0.5, 0.5, 0.5, -0.5); Elements_3 : constant Quaternion := (0.0, -1.0, 0.0, 0.0); Elements_4 : constant Quaternion := (1.0, 2.0, 3.0, 4.0); begin Assert (Normalized (Elements_1), "Elements_1 not normalized"); Assert (Normalized (Elements_2), "Elements_2 not normalized"); Assert (Normalized (Elements_3), "Elements_3 not normalized"); Assert (not Normalized (Elements_4), "Elements_4 normalized"); end Test_Normalized; procedure Test_Rotate_Axis_Angle is Axis : constant Vector4 := Vectors.Normalize ((1.0, 2.0, 3.0, 0.0)); Angle : constant GL.Types.Single := 90.0; Sin_Value : constant GL.Types.Single := EF.Sin (45.0, 360.0); Cos_Value : constant GL.Types.Single := EF.Cos (45.0, 360.0); Result : constant Quaternion := R (Axis, Angle); Expected : constant Quaternion := (Axis (X) * Sin_Value, Axis (Y) * Sin_Value, Axis (Z) * Sin_Value, Cos_Value); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; Assert (Normalized (Result), "Result not normalized"); end Test_Rotate_Axis_Angle; procedure Test_Rotate_Vectors is Start_Vector : constant Vector4 := (0.0, 1.0, 0.0, 0.0); End_Vector : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant GL.Types.Single := 90.0; Expected_1 : constant Quaternion := R (Axis, Angle); Result_1 : constant Quaternion := R (Start_Vector, End_Vector); Expected_2 : constant Quaternion := R (Axis, -Angle); Result_2 : constant Quaternion := R (End_Vector, Start_Vector); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected_1 (I), Result_1 (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected_2 (I), Result_2 (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end Test_Rotate_Vectors; procedure Test_Rotate_At_Origin is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant GL.Types.Single := 90.0; Rotation : constant Quaternion := R (Axis, Angle); Expected : constant Vector4 := (0.0, 0.0, 1.0, 0.0); Result : Vector4 := (0.0, 1.0, 0.0, 0.0); begin Rotate_At_Origin (Result, Rotation); for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end Test_Rotate_At_Origin; procedure Test_Slerp is Axis : constant Vector4 := (1.0, 0.0, 0.0, 0.0); Angle : constant GL.Types.Single := 45.0; Start_Quaternion : constant Quaternion := R (Axis, 0.0); End_Quaternion : constant Quaternion := R (Axis, 90.0); Expected : constant Quaternion := R (Axis, Angle); Result : constant Quaternion := Slerp (Start_Quaternion, End_Quaternion, 0.5); begin for I in Index_Homogeneous loop Assert (Is_Equivalent (Expected (I), Result (I)), "Unexpected Single at " & Index_Homogeneous'Image (I)); end loop; end Test_Slerp; end Test_Transforms_Singles_Quaternions;
Add extra test case to function Test_Rotate_Vectors
test: Add extra test case to function Test_Rotate_Vectors Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
07e2f38226011d34122bb0c56cbb282828ad0adc
regtests/el-utils-tests.adb
regtests/el-utils-tests.adb
----------------------------------------------------------------------- -- el-contexts-tests - Tests the EL contexts -- 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.Properties; with Util.Beans.Objects; with EL.Contexts.Default; package body EL.Utils.Tests is use Util.Tests; use Util.Beans.Objects; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Utils.Expand", Test_Expand_Properties'Access); Caller.Add_Test (Suite, "Test EL.Utils.Expand (recursion)", Test_Expand_Recursion'Access); Caller.Add_Test (Suite, "Test EL.Utils.Eval", Test_Eval'Access); end Add_Tests; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Expand_Properties (T : in out Test) is Context : EL.Contexts.Default.Default_Context; Props : Util.Properties.Manager; Result : Util.Properties.Manager; begin Props.Set ("context", "#{homedir}/context"); Props.Set ("homedir", "#{home}/#{user}"); Props.Set ("unknown", "#{not_defined}"); Props.Set ("user", "joe"); Props.Set ("home", "/home"); EL.Utils.Expand (Source => Props, Into => Result, Context => Context); Assert_Equals (T, "joe", String '(Result.Get ("user")), "Invalid expansion"); Assert_Equals (T, "/home/joe", String '(Result.Get ("homedir")), "Invalid expansion"); Assert_Equals (T, "/home/joe/context", String '(Result.Get ("context")), "Invalid expansion"); Assert_Equals (T, "", String '(Result.Get ("unknown")), "Invalid expansion"); end Test_Expand_Properties; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Expand_Recursion (T : in out Test) is Context : EL.Contexts.Default.Default_Context; Props : Util.Properties.Manager; Result : Util.Properties.Manager; begin Props.Set ("context", "#{homedir}/context"); Props.Set ("homedir", "#{home}/#{user}"); Props.Set ("user", "joe"); Props.Set ("home", "#{context}"); EL.Utils.Expand (Source => Props, Into => Result, Context => Context); Assert_Equals (T, "joe", String '(Result.Get ("user")), "Invalid expansion"); Assert_Equals (T, "/joe/context/joe/context/joe/context/joe", String '(Result.Get ("homedir")), "Invalid expansion"); end Test_Expand_Recursion; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Eval (T : in out Test) is Context : EL.Contexts.Default.Default_Context; begin Assert_Equals (T, "1", EL.Utils.Eval (Value => "1", Context => Context), "Invalid eval <empty string>"); Assert_Equals (T, "3", EL.Utils.Eval (Value => "#{2+1}", Context => Context), "Invalid eval <valid expr>"); declare Value, Result : Util.Beans.Objects.Object; begin Value := Util.Beans.Objects.To_Object (Integer '(123)); Result := EL.Utils.Eval (Value => Value, Context => Context); T.Assert (Value = Result, "Eval should return the same object"); Value := Util.Beans.Objects.To_Object (String '("345")); Result := EL.Utils.Eval (Value => Value, Context => Context); T.Assert (Value = Result, "Eval should return the same object"); end; end Test_Eval; end EL.Utils.Tests;
----------------------------------------------------------------------- -- el-contexts-tests - Tests the EL contexts -- 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.Properties; with Util.Beans.Objects; with EL.Contexts.Default; package body EL.Utils.Tests is use Util.Tests; use Util.Beans.Objects; package Caller is new Util.Test_Caller (Test, "EL.Utils"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Utils.Expand", Test_Expand_Properties'Access); Caller.Add_Test (Suite, "Test EL.Utils.Expand (recursion)", Test_Expand_Recursion'Access); Caller.Add_Test (Suite, "Test EL.Utils.Eval", Test_Eval'Access); end Add_Tests; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Expand_Properties (T : in out Test) is Context : EL.Contexts.Default.Default_Context; Props : Util.Properties.Manager; Result : Util.Properties.Manager; begin Props.Set ("context", "#{homedir}/context"); Props.Set ("homedir", "#{home}/#{user}"); Props.Set ("unknown", "#{not_defined}"); Props.Set ("user", "joe"); Props.Set ("home", "/home"); EL.Utils.Expand (Source => Props, Into => Result, Context => Context); Assert_Equals (T, "joe", String '(Result.Get ("user")), "Invalid expansion"); Assert_Equals (T, "/home/joe", String '(Result.Get ("homedir")), "Invalid expansion"); Assert_Equals (T, "/home/joe/context", String '(Result.Get ("context")), "Invalid expansion"); Assert_Equals (T, "", String '(Result.Get ("unknown")), "Invalid expansion"); end Test_Expand_Properties; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Expand_Recursion (T : in out Test) is Context : EL.Contexts.Default.Default_Context; Props : Util.Properties.Manager; Result : Util.Properties.Manager; begin Props.Set ("context", "#{homedir}/context"); Props.Set ("homedir", "#{home}/#{user}"); Props.Set ("user", "joe"); Props.Set ("home", "#{context}"); EL.Utils.Expand (Source => Props, Into => Result, Context => Context); Assert_Equals (T, "joe", String '(Result.Get ("user")), "Invalid expansion"); Assert_Equals (T, "/joe/context/joe/context/joe/context/joe", String '(Result.Get ("homedir")), "Invalid expansion"); end Test_Expand_Recursion; -- ------------------------------ -- Test expand list of properties -- ------------------------------ procedure Test_Eval (T : in out Test) is Context : EL.Contexts.Default.Default_Context; begin Assert_Equals (T, "1", EL.Utils.Eval (Value => "1", Context => Context), "Invalid eval <empty string>"); Assert_Equals (T, "3", EL.Utils.Eval (Value => "#{2+1}", Context => Context), "Invalid eval <valid expr>"); declare Value, Result : Util.Beans.Objects.Object; begin Value := Util.Beans.Objects.To_Object (Integer '(123)); Result := EL.Utils.Eval (Value => Value, Context => Context); T.Assert (Value = Result, "Eval should return the same object"); Value := Util.Beans.Objects.To_Object (String '("345")); Result := EL.Utils.Eval (Value => Value, Context => Context); T.Assert (Value = Result, "Eval should return the same object"); end; end Test_Eval; end EL.Utils.Tests;
Use the name EL.Utils for the test
Use the name EL.Utils for the test
Ada
apache-2.0
Letractively/ada-el
e9b427277438d62e8b7b183cd667338742135f99
regtests/util-log-tests.adb
regtests/util-log-tests.adb
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Directories; with Util.Test_Caller; with Util.Log; with Util.Log.Loggers; with Util.Properties; with Util.Measures; package body Util.Log.Tests is Log : constant Loggers.Logger := Loggers.Create ("util.log.test"); procedure Test_Log (T : in out Test) is pragma Unreferenced (T); L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin L.Set_Level (DEBUG_LEVEL); Log.Info ("My log message"); Log.Error ("My error message"); Log.Debug ("A debug message Not printed"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Log; -- Test configuration and creation of file procedure Test_File_Appender (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); end; end Test_File_Appender; procedure Test_Log_Perf (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); for I in 1 .. 1000 loop declare S : Util.Measures.Stamp; begin Util.Measures.Report (S, "Util.Measures.Report", 1000); end; end loop; declare L : Loggers.Logger := Loggers.Create ("util.log.test.perf"); S : Util.Measures.Stamp; begin L.Set_Level (DEBUG_LEVEL); for I in 1 .. 1000 loop L.Info ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Info message (output)", 1000); L.Set_Level (INFO_LEVEL); for I in 1 .. 10_000 loop L.Debug ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Debug message (no output)", 10_000); end; end Test_Log_Perf; -- ------------------------------ -- Test appending the log on several log files -- ------------------------------ procedure Test_List_Appender (T : in out Test) is use Ada.Strings; use Ada.Directories; Props : Util.Properties.Manager; begin for I in 1 .. 10 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Name : constant String := "log4j.appender.test" & Id; begin Props.Set (Name, "File"); Props.Set (Name & ".File", "test" & Id & ".log"); Props.Set (Name & ".layout", "date-level-message"); if I > 5 then Props.Set (Name & ".level", "INFO"); end if; end; end loop; Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); end; -- Check that we have non empty log files (up to test8.log). for I in 1 .. 8 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := "test" & Id & ".log"; begin T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); if I > 5 then T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty"); else T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty"); end if; end; end loop; end Test_List_Appender; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_File_Appender_Modes (T : in out Test) is use Ada.Directories; Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test-append.log"); Props.Set ("log4j.appender.test.append", "true"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.appender.test_global", "File"); Props.Set ("log4j.appender.test_global.File", "test-append-global.log"); Props.Set ("log4j.appender.test_global.append", "false"); Props.Set ("log4j.appender.test_global.immediateFlush", "false"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG"); Props.Set ("log4j.rootCategory", "DEBUG,test_global,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Error ("This is the error test message"); end; Props.Set ("log4j.appender.test_append", "File"); Props.Set ("log4j.appender.test_append.File", "test-append2.log"); Props.Set ("log4j.appender.test_append.append", "true"); Props.Set ("log4j.appender.test_append.immediateFlush", "true"); Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global"); Util.Log.Loggers.Initialize (Props); declare L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file"); begin L1.Info ("L1-1 Writing a info message"); L2.Info ("L2-2 {0}: {1}", "Parameter", "Value"); L1.Info ("L1-3 Done"); L2.Error ("L2-4 This is the error test2 message"); end; Props.Set ("log4j.appender.test_append.append", "plop"); Props.Set ("log4j.appender.test_append.immediateFlush", "falsex"); Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Util.Log.Loggers.Initialize (Props); T.Assert (Ada.Directories.Size ("test-append.log") > 100, "Log file test-append.log is empty"); T.Assert (Ada.Directories.Size ("test-append2.log") > 100, "Log file test-append2.log is empty"); T.Assert (Ada.Directories.Size ("test-append-global.log") > 100, "Log file test-append.log is empty"); end Test_File_Appender_Modes; package Caller is new Util.Test_Caller (Test, "Log"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender", Test_File_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)", Test_File_Appender_Modes'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender", Test_List_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)", Test_Log_Perf'Access); end Add_Tests; end Util.Log.Tests;
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2013, 2015, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with Ada.Directories; with Ada.Text_IO; with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Log; with Util.Log.Loggers; with Util.Files; with Util.Properties; with Util.Measures; package body Util.Log.Tests is Log : constant Loggers.Logger := Loggers.Create ("util.log.test"); procedure Test_Log (T : in out Test) is pragma Unreferenced (T); L : Loggers.Logger := Loggers.Create ("util.log.test.debug"); begin L.Set_Level (DEBUG_LEVEL); Log.Info ("My log message"); Log.Error ("My error message"); Log.Debug ("A debug message Not printed"); L.Info ("An info message"); L.Debug ("A debug message on logger 'L'"); end Test_Log; -- Test configuration and creation of file procedure Test_File_Appender (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); end; end Test_File_Appender; procedure Test_Log_Perf (T : in out Test) is pragma Unreferenced (T); Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test.log"); Props.Set ("log4j.logger.util.log.test.perf", "DEBUG,test"); Util.Log.Loggers.Initialize (Props); for I in 1 .. 1000 loop declare S : Util.Measures.Stamp; begin Util.Measures.Report (S, "Util.Measures.Report", 1000); end; end loop; declare L : Loggers.Logger := Loggers.Create ("util.log.test.perf"); S : Util.Measures.Stamp; begin L.Set_Level (DEBUG_LEVEL); for I in 1 .. 1000 loop L.Info ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Info message (output)", 1000); L.Set_Level (INFO_LEVEL); for I in 1 .. 10_000 loop L.Debug ("My log message: {0}: {1}", "A message", "A second parameter"); end loop; Util.Measures.Report (S, "Log.Debug message (no output)", 10_000); end; end Test_Log_Perf; -- ------------------------------ -- Test appending the log on several log files -- ------------------------------ procedure Test_List_Appender (T : in out Test) is use Ada.Strings; use Ada.Directories; Props : Util.Properties.Manager; begin for I in 1 .. 10 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Name : constant String := "log4j.appender.test" & Id; begin Props.Set (Name, "File"); Props.Set (Name & ".File", "test" & Id & ".log"); Props.Set (Name & ".layout", "date-level-message"); if I > 5 then Props.Set (Name & ".level", "INFO"); end if; end; end loop; Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG,test4,test1 , test2,test3, test4, test5 , test6 , test7,test8,"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); end; -- Check that we have non empty log files (up to test8.log). for I in 1 .. 8 loop declare Id : constant String := Fixed.Trim (Integer'Image (I), Both); Path : constant String := "test" & Id & ".log"; begin T.Assert (Ada.Directories.Exists (Path), "Log file " & Path & " not found"); if I > 5 then T.Assert (Ada.Directories.Size (Path) < 100, "Log file " & Path & " should be empty"); else T.Assert (Ada.Directories.Size (Path) > 100, "Log file " & Path & " is empty"); end if; end; end loop; end Test_List_Appender; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_File_Appender_Modes (T : in out Test) is use Ada.Directories; Props : Util.Properties.Manager; begin Props.Set ("log4j.appender.test", "File"); Props.Set ("log4j.appender.test.File", "test-append.log"); Props.Set ("log4j.appender.test.append", "true"); Props.Set ("log4j.appender.test.immediateFlush", "true"); Props.Set ("log4j.appender.test_global", "File"); Props.Set ("log4j.appender.test_global.File", "test-append-global.log"); Props.Set ("log4j.appender.test_global.append", "false"); Props.Set ("log4j.appender.test_global.immediateFlush", "false"); Props.Set ("log4j.logger.util.log.test.file", "DEBUG"); Props.Set ("log4j.rootCategory", "DEBUG,test_global,test"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Error ("This is the error test message"); end; Props.Set ("log4j.appender.test_append", "File"); Props.Set ("log4j.appender.test_append.File", "test-append2.log"); Props.Set ("log4j.appender.test_append.append", "true"); Props.Set ("log4j.appender.test_append.immediateFlush", "true"); Props.Set ("log4j.logger.util.log.test2.file", "DEBUG,test_append,test_global"); Util.Log.Loggers.Initialize (Props); declare L1 : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); L2 : constant Loggers.Logger := Loggers.Create ("util.log.test2.file"); begin L1.Info ("L1-1 Writing a info message"); L2.Info ("L2-2 {0}: {1}", "Parameter", "Value"); L1.Info ("L1-3 Done"); L2.Error ("L2-4 This is the error test2 message"); end; Props.Set ("log4j.appender.test_append.append", "plop"); Props.Set ("log4j.appender.test_append.immediateFlush", "falsex"); Props.Set ("log4j.rootCategory", "DEBUG, test.log"); Util.Log.Loggers.Initialize (Props); T.Assert (Ada.Directories.Size ("test-append.log") > 100, "Log file test-append.log is empty"); T.Assert (Ada.Directories.Size ("test-append2.log") > 100, "Log file test-append2.log is empty"); T.Assert (Ada.Directories.Size ("test-append-global.log") > 100, "Log file test-append.log is empty"); end Test_File_Appender_Modes; -- ------------------------------ -- Test file appender with different modes. -- ------------------------------ procedure Test_Console_Appender (T : in out Test) is use Ada.Directories; Props : Util.Properties.Manager; File : Ada.Text_IO.File_Type; Content : Ada.Strings.Unbounded.Unbounded_String; begin Ada.Text_IO.Create (File, Ada.Text_IO.Out_File, "test_err.log"); Ada.Text_IO.Set_Error (File); Props.Set ("log4j.appender.test_console", "Console"); Props.Set ("log4j.appender.test_console.stderr", "true"); Props.Set ("log4j.appender.test_console.level", "WARN"); Props.Set ("log4j.rootCategory", "INFO,test_console"); Util.Log.Loggers.Initialize (Props); declare L : constant Loggers.Logger := Loggers.Create ("util.log.test.file"); begin L.Debug ("Writing a debug message"); L.Debug ("{0}: {1}", "Parameter", "Value"); L.Debug ("Done"); L.Info ("INFO MESSAGE!"); L.Warn ("WARN MESSAGE!"); L.Error ("This {0} {1} {2} test message", "is", "the", "error"); end; Ada.Text_IO.Flush (Ada.Text_IO.Current_Error); Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); Ada.Text_IO.Close (File); Util.Files.Read_File ("test_err.log", Content); Util.Tests.Assert_Matches (T, ".*WARN MESSAGE!", Content, "Invalid console log (WARN)"); Util.Tests.Assert_Matches (T, ".*This is the error test message", Content, "Invalid console log (ERROR)"); exception when others => Ada.Text_IO.Set_Error (Ada.Text_IO.Standard_Error); raise; end Test_Console_Appender; package Caller is new Util.Test_Caller (Test, "Log"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Log.Loggers.Info", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Debug", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Set_Level", Test_Log'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender", Test_File_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.File_Appender (append)", Test_File_Appender_Modes'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.List_Appender", Test_List_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Appenders.Console", Test_Console_Appender'Access); Caller.Add_Test (Suite, "Test Util.Log.Loggers.Log (Perf)", Test_Log_Perf'Access); end Add_Tests; end Util.Log.Tests;
Add Test_Console_Appender procedure to check console on stderr and register it for execution
Add Test_Console_Appender procedure to check console on stderr and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
51be3878840f281c8668a980e3162ddb78660f43
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Users.Modules; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Member_List_Bean", Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Invitation_Bean", Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager; -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; -- ------------------------------ -- Load the invitation from the access key and verify that the key is still valid. -- ------------------------------ procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; begin Log.Debug ("Loading invitation from key {0}", Key); Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; end Load_Invitation; -- ------------------------------ -- Send the invitation to the user. -- ------------------------------ procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; Email : AWA.Users.Models.Email_Ref; Invitee : AWA.Users.Models.User_Ref; begin Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email)); Ctx.Start; if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (DB, Query, Found); if not Found then return; end if; Query.Clear; Query.Set_Filter ("o.email = ?"); Query.Add_Param (String '(Invitation.Get_Email)); Email.Find (DB, Query, Found); if not Found then Email.Set_User_Id (0); Email.Set_Email (String '(Invitation.Get_Email)); Email.Save (DB); Invitee.Set_Email (Email); Invitee.Set_Name (String '(Invitation.Get_Email)); Invitee.Save (DB); Email.Set_User_Id (Invitee.Get_Id); Email.Save (DB); else Invitee.Load (DB, Email.Get_User_Id); end if; Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key); Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB); Key.Save (DB); Invitation.Set_Access_Key (Key); Invitation.Set_Inviter (User); Invitation.Set_Invitee (Invitee); Invitation.Set_Workspace (WS); Invitation.Set_Create_Date (Ada.Calendar.Clock); Invitation.Save (DB); Ctx.Commit; end Send_Invitation; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- Module workspaces -- 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.Calendar; with AWA.Users.Models; with AWA.Modules.Beans; with AWA.Permissions.Services; with ADO.SQL; with Util.Log.Loggers; with AWA.Users.Modules; with AWA.Workspaces.Beans; package body AWA.Workspaces.Modules is package ASC renames AWA.Services.Contexts; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module"); package Register is new AWA.Modules.Beans (Module => Workspace_Module, Module_Access => Workspace_Module_Access); -- ------------------------------ -- Initialize the workspaces module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the workspaces module"); -- Register here any bean class, servlet, filter. Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Workspaces_Bean", Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Member_List_Bean", Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access); Register.Register (Plugin => Plugin, Name => "AWA.Workspaces.Beans.Invitation_Bean", Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager; -- Add here the creation of manager instances. end Initialize; -- ------------------------------ -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. -- ------------------------------ procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref) is User : constant AWA.Users.Models.User_Ref := Context.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; begin if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); Workspace := AWA.Workspaces.Models.Null_Workspace; return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (Session, Query, Found); if Found then Workspace := WS; return; end if; -- Create a workspace for this user. WS.Set_Owner (User); WS.Set_Create_Date (Ada.Calendar.Clock); WS.Save (Session); -- And give full control of the workspace for this user AWA.Permissions.Services.Add_Permission (Session => Session, User => User.Get_Id, Entity => WS); Workspace := WS; end Get_Workspace; -- ------------------------------ -- Load the invitation from the access key and verify that the key is still valid. -- ------------------------------ procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; begin Log.Debug ("Loading invitation from key {0}", Key); Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; end Load_Invitation; -- ------------------------------ -- Accept the invitation identified by the access key. -- ------------------------------ procedure Accept_Invitation (Module : in Workspace_Module; Key : in String) is use type Ada.Calendar.Time; Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Query : ADO.SQL.Query; DB_Key : AWA.Users.Models.Access_Key_Ref; Found : Boolean; Invitation : AWA.Workspaces.Models.Invitation_Ref; begin Log.Debug ("Accept invitation with key {0}", Key); Ctx.Start; Query.Set_Filter ("o.access_key = :key"); Query.Bind_Param ("key", Key); DB_Key.Find (DB, Query, Found); if not Found then Log.Info ("Invitation key {0} does not exist"); raise Not_Found; end if; if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then Log.Info ("Invitation key {0} has expired"); raise Not_Found; end if; Query.Set_Filter ("o.invitee_id = :user"); Query.Bind_Param ("user", DB_Key.Get_User.Get_Id); Invitation.Find (DB, Query, Found); if not Found then Log.Warn ("Invitation key {0} has been withdawn"); raise Not_Found; end if; DB_Key.Delete (DB); Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False, Value => Ada.Calendar.Clock)); Invitation.Save (DB); Ctx.Commit; end Accept_Invitation; -- ------------------------------ -- Send the invitation to the user. -- ------------------------------ procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); User : constant AWA.Users.Models.User_Ref := Ctx.Get_User; WS : AWA.Workspaces.Models.Workspace_Ref; Query : ADO.SQL.Query; Found : Boolean; Key : AWA.Users.Models.Access_Key_Ref; Email : AWA.Users.Models.Email_Ref; Invitee : AWA.Users.Models.User_Ref; begin Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email)); Ctx.Start; if User.Is_Null then Log.Error ("There is no current user. The workspace cannot be identified"); return; end if; -- Find the workspace associated with the current user. Query.Add_Param (User.Get_Id); Query.Set_Filter ("o.owner_id = ?"); WS.Find (DB, Query, Found); if not Found then return; end if; Query.Clear; Query.Set_Filter ("o.email = ?"); Query.Add_Param (String '(Invitation.Get_Email)); Email.Find (DB, Query, Found); if not Found then Email.Set_User_Id (0); Email.Set_Email (String '(Invitation.Get_Email)); Email.Save (DB); Invitee.Set_Email (Email); Invitee.Set_Name (String '(Invitation.Get_Email)); Invitee.Save (DB); Email.Set_User_Id (Invitee.Get_Id); Email.Save (DB); else Invitee.Load (DB, Email.Get_User_Id); end if; Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key); Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB); Key.Save (DB); Invitation.Set_Access_Key (Key); Invitation.Set_Inviter (User); Invitation.Set_Invitee (Invitee); Invitation.Set_Workspace (WS); Invitation.Set_Create_Date (Ada.Calendar.Clock); Invitation.Save (DB); Ctx.Commit; end Send_Invitation; end AWA.Workspaces.Modules;
Implement the Accept_Invitation procedure
Implement the Accept_Invitation procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d1dbc54aaf1ad8c89fe70234cd25946f45ffadb3
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, 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;
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Vector_Mapper -- Mapper for vector types -- Copyright (C) 2010, 2011, 2014, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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 (Ada.Strings.Unbounded.To_String (Handler.Name)); 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 (Ada.Strings.Unbounded.To_String (Handler.Name)); end Write; begin -- Allocate the unique data key. Util.Serialize.Contexts.Allocate (Key); end Util.Serialize.Mappers.Vector_Mapper;
Update Write procedure after changes in the Start_Array/End_Array procedures
Update Write procedure after changes in the Start_Array/End_Array procedures
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
66f0ef068aa7579e2a034d1237dbafde0021323a
src/asf-servlets-files.adb
src/asf-servlets-files.adb
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter ("web.dir"); begin Server.Dir := new String '(Dir); end Initialize; -- ------------------------------ -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. -- ------------------------------ function Get_Last_Modified (Server : in File_Servlet; Requet : in Requests.Request'Class) return Ada.Calendar.Time is begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ procedure Do_Get (Server : in File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Request_URI; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
----------------------------------------------------------------------- -- asf.servlets.files -- Static file servlet -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Files; with Util.Streams; with Util.Streams.Files; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Directories; with ASF.Streams; package body ASF.Servlets.Files is use Ada.Streams; use Ada.Streams.Stream_IO; use Ada.Directories; -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out File_Servlet; Context : in Servlet_Registry'Class) is Dir : constant String := Context.Get_Init_Parameter ("web.dir"); begin Server.Dir := new String '(Dir); end Initialize; -- ------------------------------ -- Returns the time the Request object was last modified, in milliseconds since -- midnight January 1, 1970 GMT. If the time is unknown, this method returns -- a negative number (the default). -- -- Servlets that support HTTP GET requests and can quickly determine their -- last modification time should override this method. This makes browser and -- proxy caches work more effectively, reducing the load on server and network -- resources. -- ------------------------------ function Get_Last_Modified (Server : in File_Servlet; Requet : in Requests.Request'Class) return Ada.Calendar.Time is begin return Ada.Calendar.Clock; end Get_Last_Modified; -- ------------------------------ -- Called by the server (via the service method) to allow a servlet to handle -- a GET request. -- -- Overriding this method to support a GET request also automatically supports -- an HTTP HEAD request. A HEAD request is a GET request that returns no body -- in the response, only the request header fields. -- -- When overriding this method, read the request data, write the response headers, -- get the response's writer or output stream object, and finally, write the -- response data. It's best to include content type and encoding. -- When using a PrintWriter object to return the response, set the content type -- before accessing the PrintWriter object. -- -- The servlet container must write the headers before committing the response, -- because in HTTP the headers must be sent before the response body. -- -- Where possible, set the Content-Length header (with the -- Response.Set_Content_Length method), to allow the servlet container -- to use a persistent connection to return its response to the client, -- improving performance. The content length is automatically set if the entire -- response fits inside the response buffer. -- -- When using HTTP 1.1 chunked encoding (which means that the response has a -- Transfer-Encoding header), do not set the Content-Length header. -- -- The GET method should be safe, that is, without any side effects for which -- users are held responsible. For example, most form queries have no side effects. -- If a client request is intended to change stored data, the request should use -- some other HTTP method. -- -- The GET method should also be idempotent, meaning that it can be safely repeated. -- Sometimes making a method safe also makes it idempotent. For example, repeating -- queries is both safe and idempotent, but buying a product online or modifying -- data is neither safe nor idempotent. -- -- If the request is incorrectly formatted, Do_Get returns an HTTP "Bad Request" -- ------------------------------ procedure Do_Get (Server : in File_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use Util.Files; URI : constant String := Request.Get_Path_Info; Path : constant String := Find_File_Path (Name => URI, Paths => Server.Dir.all); begin if not Ada.Directories.Exists (Path) or else Ada.Directories.Kind (Path) /= Ada.Directories.Ordinary_File then Response.Send_Error (Responses.SC_NOT_FOUND); return; end if; declare Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Input : Util.Streams.Files.File_Stream; begin Input.Open (Name => Path, Mode => In_File); Util.Streams.Copy (From => Input, Into => Output); end; end Do_Get; end ASF.Servlets.Files;
Use Get_Path_Info instead of the Get_Request_URI to get only the relative part of the Path and drop the servlet prefix. This path is then used to find the file path.
Use Get_Path_Info instead of the Get_Request_URI to get only the relative part of the Path and drop the servlet prefix. This path is then used to find the file path.
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
525c9e411df05cf74b25db7b7dd93d391fe00b91
src/orka/interface/orka-rendering-buffers-persistent_mapped.ads
src/orka/interface/orka-rendering-buffers-persistent_mapped.ads
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Orka.Rendering.Buffers.Pointers; generic type Index_Type is mod <>; package Orka.Rendering.Buffers.Persistent_Mapped is pragma Preelaborate; type IO_Mode is (Read, Write); type Persistent_Mapped_Buffer (Kind : Orka.Types.Composite_Type; Mode : IO_Mode) is tagged private; function Create_Buffer (Kind : Orka.Types.Composite_Type; Length : Natural; Mode : IO_Mode) return Persistent_Mapped_Buffer with Post => Create_Buffer'Result.Length = Length; -- Create a persistent mapped buffer for only writes or only reads -- -- The actual size of the buffer is n * Length where n is the number -- of regions. Each region has an index (>= 0). -- -- After writing or reading, you must call Advance_Index (once per frame). function GL_Buffer (Object : Persistent_Mapped_Buffer) return GL.Objects.Buffers.Buffer with Inline; function Length (Object : Persistent_Mapped_Buffer) return Natural with Inline; -- Number of elements in the buffer -- -- Will be less than the actual size of the buffer due to triple -- buffering. function Index_Offset (Object : Persistent_Mapped_Buffer) return Natural with Inline; -- Offset in number of elements to the start of the buffer -- -- Initially zero and incremented by Length whenever the index is -- advanced. procedure Advance_Index (Object : in out Persistent_Mapped_Buffer); ----------------------------------------------------------------------------- procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Orka.Types.Singles.Vector4_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Orka.Types.Singles.Matrix4_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Orka.Types.Doubles.Vector4_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Orka.Types.Doubles.Matrix4_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Indirect.Arrays_Indirect_Command_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Indirect.Elements_Indirect_Command_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Indirect.Dispatch_Indirect_Command_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; ----------------------------------------------------------------------------- procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Orka.Types.Singles.Vector4; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Orka.Types.Singles.Matrix4; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Orka.Types.Doubles.Vector4; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Orka.Types.Doubles.Matrix4; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Indirect.Arrays_Indirect_Command; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Indirect.Elements_Indirect_Command; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Indirect.Dispatch_Indirect_Command; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; private use Orka.Types; type Persistent_Mapped_Buffer (Kind : Orka.Types.Composite_Type; Mode : IO_Mode) is tagged record Buffer : Buffers.Buffer; Index : Index_Type; case Kind is when Single_Vector_Type => Pointer_SV : Pointers.Single_Vector4.Pointer; when Double_Vector_Type => Pointer_DV : Pointers.Double_Vector4.Pointer; when Single_Matrix_Type => Pointer_SM : Pointers.Single_Matrix4.Pointer; when Double_Matrix_Type => Pointer_DM : Pointers.Double_Matrix4.Pointer; when Arrays_Command_Type => Pointer_AC : Pointers.Arrays_Command.Pointer; when Elements_Command_Type => Pointer_EC : Pointers.Elements_Command.Pointer; when Dispatch_Command_Type => Pointer_DC : Pointers.Dispatch_Command.Pointer; end case; end record; end Orka.Rendering.Buffers.Persistent_Mapped;
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Orka.Rendering.Buffers.Pointers; generic type Index_Type is mod <>; package Orka.Rendering.Buffers.Persistent_Mapped is pragma Preelaborate; type IO_Mode is (Read, Write); type Persistent_Mapped_Buffer (Kind : Orka.Types.Composite_Type; Mode : IO_Mode) is tagged private; function Create_Buffer (Kind : Orka.Types.Composite_Type; Length : Natural; Mode : IO_Mode) return Persistent_Mapped_Buffer with Post => Create_Buffer'Result.Length = Length; -- Create a persistent mapped buffer for only writes or only reads -- -- The actual size of the buffer is n * Length where n is the number -- of regions. Each region has an index (>= 0). -- -- After writing or reading, you must call Advance_Index (once per frame). -- -- If Mode = Write, then you must wait for a fence to complete before -- writing and then set the fence after the drawing or dispatch commands -- which uses the mapped buffer. -- -- If Mode = Read, then you must set a fence after the drawing or -- dispatch commands that write to the buffer and then wait for the -- fence to complete before reading the data. function GL_Buffer (Object : Persistent_Mapped_Buffer) return GL.Objects.Buffers.Buffer with Inline; function Length (Object : Persistent_Mapped_Buffer) return Natural with Inline; -- Number of elements in the buffer -- -- Will be less than the actual size of the buffer due to triple -- buffering. function Index_Offset (Object : Persistent_Mapped_Buffer) return Natural with Inline; -- Offset in number of elements to the start of the buffer -- -- Initially zero and incremented by Length whenever the index is -- advanced. procedure Advance_Index (Object : in out Persistent_Mapped_Buffer); ----------------------------------------------------------------------------- procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Orka.Types.Singles.Vector4_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Orka.Types.Singles.Matrix4_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Orka.Types.Doubles.Vector4_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Orka.Types.Doubles.Matrix4_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Indirect.Arrays_Indirect_Command_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Indirect.Elements_Indirect_Command_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Data : Indirect.Dispatch_Indirect_Command_Array; Offset : Natural := 0) with Pre => Object.Mode = Write and Offset + Data'Length <= Object.Length; ----------------------------------------------------------------------------- procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Orka.Types.Singles.Vector4; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Orka.Types.Singles.Matrix4; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Orka.Types.Doubles.Vector4; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Orka.Types.Doubles.Matrix4; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Indirect.Arrays_Indirect_Command; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Indirect.Elements_Indirect_Command; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; procedure Write_Data (Object : Persistent_Mapped_Buffer; Value : Indirect.Dispatch_Indirect_Command; Offset : Natural) with Pre => Object.Mode = Write and Offset < Object.Length; private use Orka.Types; type Persistent_Mapped_Buffer (Kind : Orka.Types.Composite_Type; Mode : IO_Mode) is tagged record Buffer : Buffers.Buffer; Index : Index_Type; case Kind is when Single_Vector_Type => Pointer_SV : Pointers.Single_Vector4.Pointer; when Double_Vector_Type => Pointer_DV : Pointers.Double_Vector4.Pointer; when Single_Matrix_Type => Pointer_SM : Pointers.Single_Matrix4.Pointer; when Double_Matrix_Type => Pointer_DM : Pointers.Double_Matrix4.Pointer; when Arrays_Command_Type => Pointer_AC : Pointers.Arrays_Command.Pointer; when Elements_Command_Type => Pointer_EC : Pointers.Elements_Command.Pointer; when Dispatch_Command_Type => Pointer_DC : Pointers.Dispatch_Command.Pointer; end case; end record; end Orka.Rendering.Buffers.Persistent_Mapped;
Document use of fences in package Buffers.Persistent_Mapped
orka: Document use of fences in package Buffers.Persistent_Mapped Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
5ae4da727ea9eb400915cc9f0374adecafa116ea
src/gen-artifacts.ads
src/gen-artifacts.ads
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- 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 DOM.Core; with Gen.Model; with Gen.Model.Packages; with Gen.Model.Projects; -- The <b>Gen.Artifacts</b> package represents the methods and process to prepare, -- control and realize the code generation. package Gen.Artifacts is type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE); type Generator is limited interface; -- Report an error and set the exit status accordingly procedure Error (Handler : in out Generator; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is abstract; -- Get the config directory path. function Get_Config_Directory (Handler : in Generator) return String is abstract; -- Get the result directory path. function Get_Result_Directory (Handler : in Generator) return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in String := "") return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in Boolean := False) return Boolean is abstract; -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (Handler : in out Generator; Name : in String; Mode : in Iteration_Mode; Mapping : in String) is abstract; -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (Handler : in Generator; Process : not null access procedure (Dir : in String)) is abstract; -- ------------------------------ -- Model Definition -- ------------------------------ type Artifact is abstract new Ada.Finalization.Limited_Controlled with private; -- 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); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is null; -- After the generation, perform a finalization step for the generation process. procedure Finish (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- Check whether this artifact has been initialized. function Is_Initialized (Handler : in Artifact) return Boolean; private type Artifact is abstract new Ada.Finalization.Limited_Controlled with record Initialized : Boolean := False; end record; end Gen.Artifacts;
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- Copyright (C) 2011, 2012, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with DOM.Core; with Util.Log; with Gen.Model; with Gen.Model.Packages; with Gen.Model.Projects; -- The <b>Gen.Artifacts</b> package represents the methods and process to prepare, -- control and realize the code generation. package Gen.Artifacts is type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE); type Generator is limited interface and Util.Log.Logging; -- Report an error and set the exit status accordingly procedure Error (Handler : in out Generator; Message : in String; Arg1 : in String; Arg2 : in String := "") is abstract; -- Get the config directory path. function Get_Config_Directory (Handler : in Generator) return String is abstract; -- Get the result directory path. function Get_Result_Directory (Handler : in Generator) return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in String := "") return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in Boolean := False) return Boolean is abstract; -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (Handler : in out Generator; Name : in String; Mode : in Iteration_Mode; Mapping : in String) is abstract; -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (Handler : in Generator; Process : not null access procedure (Dir : in String)) is abstract; -- ------------------------------ -- Model Definition -- ------------------------------ type Artifact is abstract new Ada.Finalization.Limited_Controlled with private; -- 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); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is null; -- After the generation, perform a finalization step for the generation process. procedure Finish (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- Check whether this artifact has been initialized. function Is_Initialized (Handler : in Artifact) return Boolean; private type Artifact is abstract new Ada.Finalization.Limited_Controlled with record Initialized : Boolean := False; end record; end Gen.Artifacts;
Implement the Util.Log.Logging interface for the Generator interface
Implement the Util.Log.Logging interface for the Generator interface
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
67552bdf1a662b36338a45e18c70ed6e19b40fcd
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); return Result; end Create_Not; 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; end MAT.Expressions;
Implement the Create_And operation
Implement the Create_And operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
cc6506d9cb9e421a658471cc57910ee237547de0
mat/src/mat-expressions.ads
mat/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_CONDITION, N_THREAD); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_CONDITION, N_THREAD); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
Add INSIDE_DIRECT_FILE and INSIDE_DIRECT_FUNCTION
Add INSIDE_DIRECT_FILE and INSIDE_DIRECT_FUNCTION
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
3a6794928c93ea5296ebc5822982b70de2e0d85f
arch/ARM/STM32/driver_demos/demo_timer_pwm/src/demo_pwm_adt.adb
arch/ARM/STM32/driver_demos/demo_timer_pwm/src/demo_pwm_adt.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016-2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This demonstration illustrates the use of PWM to control the brightness of -- an LED. The effect is to make the LED increase and decrease in brightness, -- iteratively, for as long as the application runs. In effect the LED light -- waxes and wanes. See http://visualgdb.com/tutorials/arm/stm32/fpu/ for the -- inspiration. -- -- The demo uses an abstract data type PWM_Modulator to control the power to -- the LED via pulse-width-modulation. A timer is still used underneath, but -- the details are hidden. For direct use of the timer see the other demo. -- -- The demo is currently intended for the STM32F4 Discovery board for the sake -- of the convenience of the four LEDs and their association with Timer_4, but -- other boards could be used. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with STM32.Board; use STM32.Board; with STM32.Device; use STM32.Device; with STM32.PWM; use STM32.PWM; with STM32.Timers; use STM32.Timers; procedure Demo_PWM_ADT is -- demo the higher-level PWM abstract data type Selected_Timer : STM32.Timers.Timer renames Timer_4; -- NOT arbitrary! We drive the on-board LEDs that are tied to the channels -- of Timer_4 on some boards. Not all boards have this association. If you -- use a difference board, select a GPIO point connected to your selected -- timer and drive that instead. Timer_AF : constant STM32.GPIO_Alternate_Function := GPIO_AF_TIM4_2; -- Note that this value MUST match the corresponding timer selected! Output_Channel : constant Timer_Channel := Channel_2; -- arbitrary -- The LED driven by this example is determined by the channel selected. -- That is so because each channel of Timer_4 is connected to a specific -- LED in the alternate function configuration on this board. We will -- initialize all of the LEDs to be in the AF mode. The -- particular channel selected is completely arbitrary, as long as the -- selected GPIO port/pin for the LED matches the selected channel. -- -- Channel_1 is connected to the green LED. -- Channel_2 is connected to the orange LED. -- Channel_3 is connected to the red LED. -- Channel_4 is connected to the blue LED. LED_For : constant array (Timer_Channel) of User_LED := (Channel_1 => Green_LED, Channel_2 => Orange_LED, Channel_3 => Red_LED, Channel_4 => Blue_LED); Requested_Frequency : constant Hertz := 30_000; -- arbitrary Power_Control : PWM_Modulator; -- The SFP run-time library for these boards is intended for certified -- environments and so does not contain the full set of facilities defined -- by the Ada language. The elementary functions are not included, for -- example. In contrast, the Ravenscar "full" run-times do have these -- functions. function Sine (Input : Long_Float) return Long_Float; -- Therefore there are four choices: 1) use the "ravescar-full-stm32f4" -- runtime library, 2) pull the sources for the language-defined elementary -- function package into the board's run-time library and rebuild the -- run-time, 3) pull the sources for those packages into the source -- directory of your application and rebuild your application, or 4) roll -- your own approximation to the functions required by your application. -- In this demonstration we roll our own approximation to the sine function -- so that it doesn't matter which runtime library is used. function Sine (Input : Long_Float) return Long_Float is Pi : constant Long_Float := 3.14159_26535_89793_23846; X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0); B : constant Long_Float := 4.0 / Pi; C : constant Long_Float := (-4.0) / (Pi * Pi); Y : constant Long_Float := B * X + C * X * abs (X); P : constant Long_Float := 0.225; begin return P * (Y * abs (Y) - Y) + Y; end Sine; -- We use the sine function to drive the power applied to the LED, thereby -- making the LED increase and decrease in brightness. We attach the timer -- to the LED and then control how much power is supplied by changing the -- value of the timer's output compare register. The sine function drives -- that value, thus the waxing/waning effect. begin Configure_PWM_Timer (Selected_Timer'Access, Requested_Frequency); Power_Control.Attach_PWM_Channel (Selected_Timer'Access, Output_Channel, LED_For (Output_Channel), Timer_AF); Power_Control.Enable_Output; declare Arg : Long_Float := 0.0; Value : Percentage; Increment : constant Long_Float := 0.00003; -- The Increment value controls the rate at which the brightness -- increases and decreases. The value is more or less arbitrary, but -- note that the effect of optimization is observable. begin loop Value := Percentage (50.0 * (1.0 + Sine (Arg))); Set_Duty_Cycle (Power_Control, Value); Arg := Arg + Increment; end loop; end; end Demo_PWM_ADT;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016-2017, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This demonstration illustrates the use of PWM to control the brightness of -- an LED. The effect is to make the LED increase and decrease in brightness, -- iteratively, for as long as the application runs. In effect the LED light -- waxes and wanes. See http://visualgdb.com/tutorials/arm/stm32/fpu/ for the -- inspiration. -- -- The demo uses an abstract data type PWM_Modulator to control the power to -- the LED via pulse-width-modulation. A timer is still used underneath, but -- the details are hidden. For direct use of the timer see the other demo. -- -- The demo is currently intended for the STM32F4 Discovery board for the sake -- of the convenience of the four LEDs and their association with Timer_4, but -- other boards could be used. with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler); with STM32.Board; use STM32.Board; with STM32.Device; use STM32.Device; with STM32.PWM; use STM32.PWM; with STM32.Timers; use STM32.Timers; procedure Demo_PWM_ADT is -- demo the higher-level PWM abstract data type Selected_Timer : STM32.Timers.Timer renames Timer_4; -- NOT arbitrary! We drive the on-board LEDs that are tied to the channels -- of Timer_4 on some boards. Not all boards have this association. If you -- use a different board, select a GPIO point connected to your selected -- timer and drive that instead. Timer_AF : constant STM32.GPIO_Alternate_Function := GPIO_AF_TIM4_2; -- Note that this value MUST match the corresponding timer selected! Output_Channel : constant Timer_Channel := Channel_2; -- arbitrary -- The LED driven by this example is determined by the channel selected. -- That is so because each channel of Timer_4 is connected to a specific -- LED in the alternate function configuration on this board. We will -- initialize all of the LEDs to be in the AF mode. The -- particular channel selected is completely arbitrary, as long as the -- selected GPIO port/pin for the LED matches the selected channel. -- -- Channel_1 is connected to the green LED. -- Channel_2 is connected to the orange LED. -- Channel_3 is connected to the red LED. -- Channel_4 is connected to the blue LED. LED_For : constant array (Timer_Channel) of User_LED := (Channel_1 => Green_LED, Channel_2 => Orange_LED, Channel_3 => Red_LED, Channel_4 => Blue_LED); Requested_Frequency : constant Hertz := 30_000; -- arbitrary Power_Control : PWM_Modulator; -- The SFP run-time library for these boards is intended for certified -- environments and so does not contain the full set of facilities defined -- by the Ada language. The elementary functions are not included, for -- example. In contrast, the Ravenscar "full" run-times do have these -- functions. function Sine (Input : Long_Float) return Long_Float; -- Therefore there are four choices: 1) use the "ravescar-full-stm32f4" -- runtime library, 2) pull the sources for the language-defined elementary -- function package into the board's run-time library and rebuild the -- run-time, 3) pull the sources for those packages into the source -- directory of your application and rebuild your application, or 4) roll -- your own approximation to the functions required by your application. -- In this demonstration we roll our own approximation to the sine function -- so that it doesn't matter which runtime library is used. function Sine (Input : Long_Float) return Long_Float is Pi : constant Long_Float := 3.14159_26535_89793_23846; X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0); B : constant Long_Float := 4.0 / Pi; C : constant Long_Float := (-4.0) / (Pi * Pi); Y : constant Long_Float := B * X + C * X * abs (X); P : constant Long_Float := 0.225; begin return P * (Y * abs (Y) - Y) + Y; end Sine; -- We use the sine function to drive the power applied to the LED, thereby -- making the LED increase and decrease in brightness. We attach the timer -- to the LED and then control how much power is supplied by changing the -- value of the timer's output compare register. The sine function drives -- that value, thus the waxing/waning effect. begin Configure_PWM_Timer (Selected_Timer'Access, Requested_Frequency); Power_Control.Attach_PWM_Channel (Selected_Timer'Access, Output_Channel, LED_For (Output_Channel), Timer_AF); Power_Control.Enable_Output; declare Arg : Long_Float := 0.0; Value : Percentage; Increment : constant Long_Float := 0.00003; -- The Increment value controls the rate at which the brightness -- increases and decreases. The value is more or less arbitrary, but -- note that the effect of compiler optimization is observable. begin loop Value := Percentage (50.0 * (1.0 + Sine (Arg))); Power_Control.Set_Duty_Cycle (Value); Arg := Arg + Increment; end loop; end; end Demo_PWM_ADT;
fix typo in comment improvement comment re: optimization use distinguished receiver syntax consistently
fix typo in comment improvement comment re: optimization use distinguished receiver syntax consistently
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
3749a7c144d5ed2cfdb7ae0fed346c8d88dcdb56
src/gen-model-mappings.ads
src/gen-model-mappings.ads
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB, T_TABLE); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; end record; type Mapping_Definition_Access is access all Mapping_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_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); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); subtype Map is Mapping_Maps.Map; subtype Cursor is Mapping_Maps.Cursor; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package Gen.Model.Mappings is ADA_MAPPING : constant String := "Ada05"; MySQL_MAPPING : constant String := "MySQL"; SQLite_MAPPING : constant String := "SQLite"; type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB, T_BEAN, T_TABLE); -- ------------------------------ -- Mapping Definition -- ------------------------------ type Mapping_Definition is new Definition with record Target : Ada.Strings.Unbounded.Unbounded_String; Kind : Basic_Type := T_INTEGER; end record; type Mapping_Definition_Access is access all Mapping_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Mapping_Definition; Name : String) return Util.Beans.Objects.Object; -- Find the mapping for the given type name. function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_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); -- Setup the type mapping for the language identified by the given name. procedure Set_Mapping_Name (Name : in String); package Mapping_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String, Element_Type => Mapping_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => Ada.Strings.Unbounded."="); subtype Map is Mapping_Maps.Map; subtype Cursor is Mapping_Maps.Cursor; end Gen.Model.Mappings;
Add T_BEAN
Add T_BEAN
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
a82e93917a5387321f1b3892f5350a1932548f7a
src/ado-queries-loaders.adb
src/ado-queries-loaders.adb
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- 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 Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is use ADO.Drivers; begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query/sql-count/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Drivers.Connections.Configuration'Class) is Paths : constant String := Config.Get_Property ("ado.queries.paths"); Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true"; File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Manager.Files (File.File).File := File; Manager.Files (File.File).Last_Modified := 0; Manager.Files (File.File).Next_Check := 0; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.File := File; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
----------------------------------------------------------------------- -- ado-queries-loaders -- Loader for Database Queries -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Directories; with Util.Files; with Util.Log.Loggers; with Util.Beans.Objects; with Util.Serialize.IO.XML; with Util.Serialize.Mappers.Record_Mapper; with ADO.Configs; package body ADO.Queries.Loaders is use Util.Log; use ADO.Drivers.Connections; use Interfaces; use Ada.Calendar; Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders"); Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970, Month => 1, Day => 1); -- Check for file modification time at most every 60 seconds. FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60; -- The list of query files defined by the application. Query_Files : Query_File_Access := null; Last_Query : Query_Index := 0; Last_File : File_Index := 0; -- Convert a Time to an Unsigned_32. function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32; pragma Inline_Always (To_Unsigned_32); -- Get the modification time of the XML query file associated with the query. function Modification_Time (File : in Query_File_Info) return Unsigned_32; -- Initialize the query SQL pattern with the value procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Register the query definition in the query file. Registration is done -- in the package elaboration phase. -- ------------------------------ procedure Register (File : in Query_File_Access; Query : in Query_Definition_Access) is begin Last_Query := Last_Query + 1; Query.File := File; Query.Next := File.Queries; Query.Query := Last_Query; File.Queries := Query; if File.Next = null and then Query_Files /= File then Last_File := Last_File + 1; File.Next := Query_Files; File.File := Last_File; Query_Files := File; end if; end Register; function Find_Driver (Name : in String) return Integer; function Find_Driver (Name : in String) return Integer is begin if Name'Length = 0 then return 0; end if; declare Driver : constant Drivers.Connections.Driver_Access := Drivers.Connections.Get_Driver (Name); begin if Driver = null then -- There is no problem to have an SQL query for unsupported drivers, but still -- report some warning. Log.Warn ("Database driver {0} not found", Name); return -1; end if; return Integer (Driver.Get_Driver_Index); end; end Find_Driver; -- ------------------------------ -- Convert a Time to an Unsigned_32. -- ------------------------------ function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is D : constant Duration := Duration '(T - Base_Time); begin return Unsigned_32 (D); end To_Unsigned_32; -- ------------------------------ -- Get the modification time of the XML query file associated with the query. -- ------------------------------ function Modification_Time (File : in Query_File_Info) return Unsigned_32 is Path : constant String := To_String (File.Path); begin return To_Unsigned_32 (Ada.Directories.Modification_Time (Path)); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); return 0; end Modification_Time; -- ------------------------------ -- Returns True if the XML query file must be reloaded. -- ------------------------------ function Is_Modified (File : in out Query_File_Info) return Boolean is Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock); begin -- Have we passed the next check time? if File.Next_Check > Now then return False; end if; -- Next check in N seconds (60 by default). File.Next_Check := Now + FILE_CHECK_DELTA_TIME; -- See if the file was changed. declare M : constant Unsigned_32 := Modification_Time (File); begin if File.Last_Modified = M then return False; end if; File.Last_Modified := M; return True; end; end Is_Modified; -- ------------------------------ -- Initialize the query SQL pattern with the value -- ------------------------------ procedure Set_Query_Pattern (Into : in out Query_Pattern; Value : in Util.Beans.Objects.Object) is begin Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value); end Set_Query_Pattern; procedure Read_Query (Manager : in Query_Manager; File : in out Query_File_Info) is type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE, FIELD_PROPERTY_NAME, FIELD_QUERY_NAME, FIELD_SQL_DRIVER, FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY); -- The Query_Loader holds context and state information for loading -- the XML query file and initializing the Query_Definition. type Query_Loader is record -- File : Query_File_Access; Hash_Value : Unbounded_String; Query_Def : Query_Definition_Access; Query : Query_Info_Ref.Ref; Driver : Integer; end record; type Query_Loader_Access is access all Query_Loader; procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called by the de-serialization when a given field is recognized. -- ------------------------------ procedure Set_Member (Into : in out Query_Loader; Field : in Query_Info_Fields; Value : in Util.Beans.Objects.Object) is use ADO.Drivers; begin case Field is when FIELD_CLASS_NAME => Append (Into.Hash_Value, " class="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_TYPE => Append (Into.Hash_Value, " type="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_PROPERTY_NAME => Append (Into.Hash_Value, " name="); Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value)); when FIELD_QUERY_NAME => Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value)); Into.Driver := 0; if Into.Query_Def /= null then Into.Query := Query_Info_Ref.Create; end if; when FIELD_SQL_DRIVER => Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value)); when FIELD_SQL => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_SQL_COUNT => if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)), Value); end if; Into.Driver := 0; when FIELD_QUERY => if Into.Query_Def /= null then -- Now we can safely setup the query info associated with the query definition. Manager.Queries (Into.Query_Def.Query) := Into.Query; end if; Into.Query_Def := null; end case; end Set_Member; package Query_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader, Element_Type_Access => Query_Loader_Access, Fields => Query_Info_Fields, Set_Member => Set_Member); Loader : aliased Query_Loader; Sql_Mapper : aliased Query_Mapper.Mapper; Reader : Util.Serialize.IO.XML.Parser; Mapper : Util.Serialize.Mappers.Processing; Path : constant String := To_String (File.Path); begin Log.Info ("Reading XML query {0}", Path); -- Loader.File := Into; Loader.Driver := 0; -- Create the mapping to load the XML query file. Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME); Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE); Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME); Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME); Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL); Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT); Sql_Mapper.Add_Mapping ("query/sql-count/@driver", FIELD_SQL_DRIVER); Sql_Mapper.Add_Mapping ("query", FIELD_QUERY); Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access); -- Set the context for Set_Member. Query_Mapper.Set_Context (Mapper, Loader'Access); -- Read the XML query file. Reader.Parse (Path, Mapper); File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME; exception when Ada.IO_Exceptions.Name_Error => Log.Error ("XML query file '{0}' does not exist", Path); end Read_Query; -- ------------------------------ -- Read the query definition. -- ------------------------------ procedure Read_Query (Manager : in Query_Manager; Into : in Query_Definition_Access) is begin if Manager.Queries (Into.Query).Is_Null or else Is_Modified (Manager.Files (Into.File.File)) then Read_Query (Manager, Manager.Files (Into.File.File)); end if; end Read_Query; -- ------------------------------ -- Initialize the queries to look in the list of directories specified by <b>Paths</b>. -- Each search directory is separated by ';' (yes, even on Unix). -- When <b>Load</b> is true, read the XML query file and initialize the query -- definitions from that file. -- ------------------------------ procedure Initialize (Manager : in out Query_Manager; Config : in ADO.Drivers.Connections.Configuration'Class) is Paths : constant String := Config.Get_Property (Configs.QUERY_PATHS_CONFIG); Load : constant Boolean := Config.Get_Property (Configs.QUERY_LOAD_CONFIG) = "true"; File : Query_File_Access := Query_Files; begin Log.Info ("Initializing query search paths to {0}", Paths); if Manager.Queries = null then Manager.Queries := new Query_Table (1 .. Last_Query); end if; if Manager.Files = null then Manager.Files := new File_Table (1 .. Last_File); end if; Manager.Driver := Config.Get_Driver; while File /= null loop declare Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all, Paths => Paths); begin Manager.Files (File.File).File := File; Manager.Files (File.File).Last_Modified := 0; Manager.Files (File.File).Next_Check := 0; Manager.Files (File.File).Path := To_Unbounded_String (Path); if Load then Read_Query (Manager, Manager.Files (File.File)); end if; end; File := File.Next; end loop; end Initialize; -- ------------------------------ -- Find the query identified by the given name. -- ------------------------------ function Find_Query (Name : in String) return Query_Definition_Access is File : Query_File_Access := Query_Files; begin while File /= null loop declare Query : Query_Definition_Access := File.Queries; begin while Query /= null loop if Query.Name.all = Name then return Query; end if; Query := Query.Next; end loop; end; File := File.Next; end loop; Log.Warn ("Query {0} not found", Name); return null; end Find_Query; package body File is begin File.Name := Name'Access; File.Sha1_Map := Hash'Access; end File; package body Query is begin Query.Name := Query_Name'Access; Query.File := File; Register (File => File, Query => Query'Access); end Query; end ADO.Queries.Loaders;
Use Configs.QUERY_PATHS_CONFIG and Configs.QUERY_LOAD_CONFIG constants
Use Configs.QUERY_PATHS_CONFIG and Configs.QUERY_LOAD_CONFIG constants
Ada
apache-2.0
stcarrez/ada-ado
c23da9a54bba085f1ee772b6602f49b7e8d129e3
awa/plugins/awa-storages/src/awa-storages.ads
awa/plugins/awa-storages/src/awa-storages.ads
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A data in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- -- Data.Set_Storage (Storage => AWA.Storages.Models.DATABASE); -- -- To save a file in the store, we can use the `Save` operation of the storage service. -- It will read the file and put in in the corresponding persistent store (the database -- in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- === Local file === -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading locally we -- also indicate whether the file will be read or written. A file that is in `READ` mode -- can be shared by several tasks or processes. A file that is in `WRITE` mode will have -- a specific copy for the caller. An optional expiration parameter indicate when the -- local file representation can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png] -- -- @include Storages.hbm.xml package AWA.Storages is end AWA.Storages;
----------------------------------------------------------------------- -- awa-storages -- Storage module -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Storages</b> module provides a set of storage services allowing an application -- to store data files, documents, images in a persistent area. The persistent store can -- be on a file system, in the database or provided by a remote service such as -- Amazon Simple Storage Service. -- -- == Creating a storage == -- A data in the storage is represented by a `Storage_Ref` instance. The data itself -- can be physically stored in a file system (`FILE` mode), in the database (`DATABASE` -- mode) or on a remote server (`URL` mode). To put a file in the storage space, first create -- the storage object instance: -- -- Data : AWA.Storages.Models.Storage_Ref; -- -- Then setup the storage mode that you want. The storage service uses this information -- to save the data in a file, in the database or in a remote service (in the future). -- To save a file in the store, we can use the `Save` operation of the storage service. -- It will read the file and put in in the corresponding persistent store (the database -- in this example). -- -- Service.Save (Into => Data, Path => Path_To_The_File, -- Storage => AWA.Storages.Models.DATABASE); -- -- Upon successful completion, the storage instance `Data` will be allocated a unique -- identifier that can be retrieved by `Get_Id` or `Get_Key`. -- -- == Getting the data == -- Several operations are defined to retrieve the data. Each of them has been designed -- to optimize the retrieval and -- -- * The data can be retrieved in a local file. -- This mode is useful if an external program must be launched and be able to read -- the file. If the storage mode of the data is `FILE`, the path of the file on -- the storage file system is used. For other storage modes, the file is saved -- in a temporary file. In that case the `Store_Local` database table is used -- to track such locally saved data. -- -- * The data can be returned as a stream. -- When the application has to read the data, opening a read stream connection is -- the most efficient mechanism. -- -- === Local file === -- To access the data by using a local file, we must define a local storage reference: -- -- Data : AWA.Storages.Models.Store_Local_Ref; -- -- and use the `Load` operation with the storage identifier. When loading locally we -- also indicate whether the file will be read or written. A file that is in `READ` mode -- can be shared by several tasks or processes. A file that is in `WRITE` mode will have -- a specific copy for the caller. An optional expiration parameter indicate when the -- local file representation can expire. -- -- Service.Load (From => Id, Into => Data, Mode => READ, Expire => ONE_DAY); -- -- Once the load operation succeeded, the data is stored on the file system and -- the local path is obtained by using the `Get_Path` operation: -- -- Path : constant String := Data.Get_Path; -- -- == Ada Beans == -- @include storages.xml -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_storage_model.png] -- -- @include Storages.hbm.xml package AWA.Storages is end AWA.Storages;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
024e51ab76465425bc7eb8a738bb5b64cd1f45ea
src/gen-commands-layout.ads
src/gen-commands-layout.ads
----------------------------------------------------------------------- -- gen-commands-layout -- Layout creation command for dynamo -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Layout is -- ------------------------------ -- Layout Creation Command -- ------------------------------ -- This command adds a XHTML layout to the web application. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Layout;
----------------------------------------------------------------------- -- gen-commands-layout -- Layout creation command for dynamo -- Copyright (C) 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Layout is -- ------------------------------ -- Layout Creation Command -- ------------------------------ -- This command adds a XHTML layout to the web application. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler); -- Write the help associated with the command. overriding procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Layout;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
1df8b31de8fc503c40d8da38c9788ab9c725ff53
src/util-streams-pipes.ads
src/util-streams-pipes.ads
----------------------------------------------------------------------- -- util-streams-pipes -- Pipe stream to or from a process -- Copyright (C) 2011, 2013, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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; -- The <b>Util.Streams.Pipes</b> package defines a pipe stream to or from a process. -- The process is created and launched by the <b>Open</b> operation. The pipe allows -- to read or write to the process through the <b>Read</b> and <b>Write</b> operation. 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); -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ); -- Close the pipe and wait for the external process to terminate. overriding procedure Close (Stream : in out Pipe_Stream); -- Get the process exit status. function Get_Exit_Status (Stream : in Pipe_Stream) return Integer; -- Returns True if the process is running. function Is_Running (Stream : in Pipe_Stream) return Boolean; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record Proc : Util.Processes.Process; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Pipe_Stream); end Util.Streams.Pipes;
----------------------------------------------------------------------- -- util-streams-pipes -- Pipe stream to or from a process -- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Processes; -- === Pipes === -- The <b>Util.Streams.Pipes</b> package defines a pipe stream to or from a process. -- The process is created and launched by the <b>Open</b> operation. The pipe allows -- to read or write to the process through the <b>Read</b> and <b>Write</b> operation. 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); -- Open a pipe to read or write to an external process. The pipe is created and the -- command is executed with the input and output streams redirected through the pipe. procedure Open (Stream : in out Pipe_Stream; Command : in String; Mode : in Pipe_Mode := READ); -- Close the pipe and wait for the external process to terminate. overriding procedure Close (Stream : in out Pipe_Stream); -- Get the process exit status. function Get_Exit_Status (Stream : in Pipe_Stream) return Integer; -- Returns True if the process is running. function Is_Running (Stream : in Pipe_Stream) return Boolean; -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Pipe_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Pipe_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record Proc : Util.Processes.Process; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Pipe_Stream); end Util.Streams.Pipes;
Document the streams framework
Document the streams framework
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8a09350aba20b0fbd12bb0d177095b4dba6564cc
regtests/util-properties-tests.ads
regtests/util-properties-tests.ads
----------------------------------------------------------------------- -- Util -- Utilities -- Copyright (C) 2009, 2010, 2011, 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 Util.Tests; package Util.Properties.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Property (T : in out Test); procedure Test_Integer_Property (T : in out Test); procedure Test_Load_Property (T : in out Test); procedure Test_Load_Strip_Property (T : in out Test); procedure Test_Copy_Property (T : in out Test); procedure Test_Set_Preserve_Original (T : in out Test); procedure Test_Remove_Preserve_Original (T : in out Test); procedure Test_Missing_Property (T : in out Test); end Util.Properties.Tests;
----------------------------------------------------------------------- -- Util -- Utilities -- Copyright (C) 2009, 2010, 2011, 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 Util.Tests; package Util.Properties.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Property (T : in out Test); procedure Test_Integer_Property (T : in out Test); procedure Test_Load_Property (T : in out Test); procedure Test_Load_Strip_Property (T : in out Test); procedure Test_Copy_Property (T : in out Test); procedure Test_Set_Preserve_Original (T : in out Test); procedure Test_Remove_Preserve_Original (T : in out Test); procedure Test_Missing_Property (T : in out Test); procedure Test_Load_Ini_Property (T : in out Test); end Util.Properties.Tests;
Declare the Test_Load_Ini_Property procedure
Declare the Test_Load_Ini_Property procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
15438181d5b533eae2c38480a4d1ed2f8067555e
src/orka/implementation/orka-resources-textures-ktx.adb
src/orka/implementation/orka-resources-textures-ktx.adb
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System; with Ada.Exceptions; with Ada.Real_Time; with Ada.Unchecked_Deallocation; with GL.Low_Level.Enums; with GL.Types; with GL.Pixels.Queries; with Orka.Logging; with Orka.KTX; package body Orka.Resources.Textures.KTX is use Orka.Logging; package Messages is new Orka.Logging.Messages (Resource_Loader); type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record Data : Loaders.Resource_Data; Manager : Managers.Manager_Ptr; end record; overriding procedure Execute (Object : KTX_Load_Job; Enqueue : not null access procedure (Element : Jobs.Job_Ptr)); ----------------------------------------------------------------------------- use all type Ada.Real_Time.Time; overriding procedure Execute (Object : KTX_Load_Job; Enqueue : not null access procedure (Element : Jobs.Job_Ptr)) is Bytes : Byte_Array_Pointers.Constant_Reference := Object.Data.Bytes.Get; Path : String renames SU.To_String (Object.Data.Path); T1 : Ada.Real_Time.Time renames Object.Data.Start_Time; T2 : constant Ada.Real_Time.Time := Clock; use Ada.Streams; use GL.Low_Level.Enums; use type GL.Types.Size; T3, T4, T5, T6 : Ada.Real_Time.Time; begin if not Orka.KTX.Valid_Identifier (Bytes) then raise Texture_Load_Error with Path & " is not a KTX file"; end if; declare Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes); Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels); Resource : constant Texture_Ptr := new Texture'(others => <>); Texture : GL.Objects.Textures.Texture (Header.Kind); Width : constant GL.Types.Size := Header.Width; Height : GL.Types.Size := Header.Height; Depth : GL.Types.Size := Header.Depth; begin T3 := Clock; -- Allocate storage case Header.Kind is when Texture_2D_Array => Depth := Header.Array_Elements; when Texture_1D_Array => Height := Header.Array_Elements; pragma Assert (Depth = 0); when Texture_Cube_Map_Array => -- For a cube map array, depth is the number of layer-faces Depth := Header.Array_Elements * 6; when Texture_3D => null; when Texture_2D | Texture_Cube_Map => pragma Assert (Depth = 0); when Texture_1D => if Header.Compressed then raise Texture_Load_Error with Path & " has unknown 1D compressed format"; end if; pragma Assert (Height = 0); pragma Assert (Depth = 0); when others => raise Program_Error; end case; if Header.Compressed then Texture.Allocate_Storage (Levels, Header.Compressed_Format, Width, Height, Depth); else Texture.Allocate_Storage (Levels, Header.Internal_Format, Width, Height, Depth); end if; T4 := Clock; -- TODO Handle KTXorientation key value pair -- Upload texture data declare Image_Size_Index : Stream_Element_Offset := Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value); Cube_Map : constant Boolean := Header.Kind = Texture_Cube_Map; begin for Level in 0 .. Levels - 1 loop declare Face_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index); -- If not Cube_Map, then Face_Size is the size of the whole level Cube_Padding : constant Natural := 3 - ((Face_Size + 3) mod 4); Image_Size : constant Natural := (if Cube_Map then (Face_Size + Cube_Padding) * 6 else Face_Size); -- If Cube_Map then Levels = 1 so no need to add it to the expression -- Compute size of the whole mipmap level Mip_Padding : constant Natural := 3 - ((Image_Size + 3) mod 4); Mipmap_Size : constant Natural := 4 + Image_Size + Mip_Padding; Offset : constant Stream_Element_Offset := Image_Size_Index + 4; pragma Assert (Offset + Stream_Element_Offset (Image_Size) - 1 <= Bytes.Value'Last); Image_Data : constant System.Address := Bytes (Offset)'Address; -- TODO Unpack_Alignment must be 4, but Load_From_Data wants 1 | 2 | 4 -- depending on Header.Data_Type begin case Header.Kind is when Texture_1D => Height := 1; Depth := 1; when Texture_1D_Array | Texture_2D => Depth := 1; when Texture_2D_Array | Texture_3D => null; when Texture_Cube_Map | Texture_Cube_Map_Array => -- Texture_Cube_Map uses 2D storage, but 3D load operation -- according to table 8.15 of the OpenGL specification -- For a cube map, depth is the number of faces, for -- a cube map array, depth is the number of layer-faces Depth := GL.Types.Size'Max (1, Header.Array_Elements) * 6; when others => raise Program_Error; end case; if Header.Compressed then Texture.Load_From_Data (Level, 0, 0, 0, Width, Height, Depth, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data); else Texture.Load_From_Data (Level, 0, 0, 0, Width, Height, Depth, Header.Format, Header.Data_Type, Image_Data); end if; Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size); end; end loop; end; T5 := Clock; -- Generate a full mipmap pyramid if Mipmap_Levels = 0 if Header.Mipmap_Levels = 0 then Texture.Generate_Mipmap; end if; T6 := Clock; Resource.Texture.Replace_Element (Texture); -- Register resource at the resource manager Object.Manager.Add_Resource (Path, Resource_Ptr (Resource)); Messages.Insert (Info, "Loaded texture " & Path & " in " & Logging.Trim (Logging.Image (T6 - T1))); Messages.Insert (Info, " dimensions: " & Logging.Trim (Header.Width'Image) & " x " & Logging.Trim (Header.Height'Image) & " x " & Logging.Trim (Header.Depth'Image) & ", array length:" & Header.Array_Elements'Image & ", mipmap levels:" & Levels'Image); Messages.Insert (Info, " kind: " & Header.Kind'Image); if Header.Compressed then Messages.Insert (Info, " compressed format: " & Header.Compressed_Format'Image); else Messages.Insert (Info, " internal: " & Header.Internal_Format'Image); Messages.Insert (Info, " format: " & Header.Format'Image); Messages.Insert (Info, " type: " & Header.Data_Type'Image); end if; Messages.Insert (Info, " statistics:"); Messages.Insert (Info, " reading file: " & Logging.Image (T2 - T1)); Messages.Insert (Info, " parsing header: " & Logging.Image (T3 - T2)); Messages.Insert (Info, " storage: " & Logging.Image (T4 - T3)); Messages.Insert (Info, " buffers: " & Logging.Image (T5 - T4)); if Header.Mipmap_Levels = 0 then Messages.Insert (Info, " generating mipmap:" & Logging.Image (T6 - T5)); end if; end; exception when Error : Orka.KTX.Invalid_Enum_Error => declare Message : constant String := Ada.Exceptions.Exception_Message (Error); begin raise Texture_Load_Error with Path & " has " & Message; end; end Execute; ----------------------------------------------------------------------------- -- Loader -- ----------------------------------------------------------------------------- type KTX_Loader is limited new Loaders.Loader with record Manager : Managers.Manager_Ptr; end record; overriding function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx"); overriding procedure Load (Object : KTX_Loader; Data : Loaders.Resource_Data; Enqueue : not null access procedure (Element : Jobs.Job_Ptr); Location : Locations.Location_Ptr) is Job : constant Jobs.Job_Ptr := new KTX_Load_Job' (Jobs.Abstract_Job with Data => Data, Manager => Object.Manager); begin Enqueue (Job); end Load; function Create_Loader (Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr is (new KTX_Loader'(Manager => Manager)); ----------------------------------------------------------------------------- -- Writer -- ----------------------------------------------------------------------------- procedure Write_Texture (Texture : GL.Objects.Textures.Texture; Location : Locations.Writable_Location_Ptr; Path : String) is package Textures renames GL.Objects.Textures; package Pointers is new Textures.Texture_Pointers (Byte_Pointers); Format : GL.Pixels.Format := GL.Pixels.RGBA; Data_Type : GL.Pixels.Data_Type := GL.Pixels.Float; -- Note: unused if texture is compressed use Ada.Streams; use all type GL.Low_Level.Enums.Texture_Kind; use type GL.Types.Size; Compressed : constant Boolean := Texture.Compressed (0); Header : Orka.KTX.Header (Compressed); function Convert (Bytes : in out GL.Types.UByte_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); procedure Free is new Ada.Unchecked_Deallocation (Object => GL.Types.UByte_Array, Name => GL.Types.UByte_Array_Access); begin for Index in Bytes'Range loop declare Target_Index : constant Stream_Element_Offset := Stream_Element_Offset (Index - Bytes'First + 1); begin Result (Target_Index) := Stream_Element (Bytes (Index)); end; end loop; Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Convert (Bytes : in out Pointers.Element_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); begin Result.all := Bytes.all; Pointers.Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Get_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : Pointers.Element_Array_Access; begin Data := Pointers.Get_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Format, Data_Type); return Convert (Data); end Get_Data; function Get_Compressed_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : GL.Types.UByte_Array_Access; begin Data := Textures.Get_Compressed_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Texture.Compressed_Format (0)); return Convert (Data); end Get_Compressed_Data; begin Header.Kind := Texture.Kind; Header.Width := Texture.Width (0); case Texture.Kind is when Texture_3D => Header.Height := Texture.Height (0); Header.Depth := Texture.Depth (0); when Texture_2D | Texture_2D_Array | Texture_Cube_Map | Texture_Cube_Map_Array => Header.Height := Texture.Height (0); Header.Depth := 0; when Texture_1D | Texture_1D_Array => Header.Height := 0; Header.Depth := 0; when others => raise Program_Error; end case; case Texture.Kind is when Texture_1D_Array => Header.Array_Elements := Texture.Height (0); when Texture_2D_Array => Header.Array_Elements := Texture.Depth (0); when Texture_Cube_Map_Array => Header.Array_Elements := Texture.Depth (0) / 6; when Texture_1D | Texture_2D | Texture_3D | Texture_Cube_Map => Header.Array_Elements := 0; when others => raise Program_Error; end case; Header.Mipmap_Levels := 1; Header.Bytes_Key_Value := 0; if Compressed then Header.Compressed_Format := Texture.Compressed_Format (0); else declare Internal_Format : constant GL.Pixels.Internal_Format := Texture.Internal_Format (0); begin Format := GL.Pixels.Queries.Get_Texture_Format (Internal_Format, Texture.Kind); Data_Type := GL.Pixels.Queries.Get_Texture_Type (Internal_Format, Texture.Kind); Header.Internal_Format := Internal_Format; Header.Format := Format; Header.Data_Type := Data_Type; end; end if; declare Data : constant Byte_Array_Pointers.Pointer := (if Compressed then Get_Compressed_Data (0) else Get_Data (0)); Bytes : constant Byte_Array_Pointers.Pointer := Orka.KTX.Create_KTX_Bytes (Header, Data.Get); begin Location.Write_Data (Path, Bytes.Get); end; end Write_Texture; end Orka.Resources.Textures.KTX;
-- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System; with Ada.Exceptions; with Ada.Real_Time; with Ada.Unchecked_Deallocation; with GL.Low_Level.Enums; with GL.Types; with GL.Pixels.Queries; with Orka.Logging; with Orka.KTX; package body Orka.Resources.Textures.KTX is use Orka.Logging; package Messages is new Orka.Logging.Messages (Resource_Loader); type KTX_Load_Job is new Jobs.Abstract_Job and Jobs.GPU_Job with record Data : Loaders.Resource_Data; Manager : Managers.Manager_Ptr; end record; overriding procedure Execute (Object : KTX_Load_Job; Enqueue : not null access procedure (Element : Jobs.Job_Ptr)); ----------------------------------------------------------------------------- use all type Ada.Real_Time.Time; overriding procedure Execute (Object : KTX_Load_Job; Enqueue : not null access procedure (Element : Jobs.Job_Ptr)) is Bytes : Byte_Array_Pointers.Constant_Reference := Object.Data.Bytes.Get; Path : String renames SU.To_String (Object.Data.Path); T1 : Ada.Real_Time.Time renames Object.Data.Start_Time; T2 : constant Ada.Real_Time.Time := Clock; use Ada.Streams; use GL.Low_Level.Enums; use type GL.Types.Size; T3, T4, T5, T6 : Ada.Real_Time.Time; begin if not Orka.KTX.Valid_Identifier (Bytes) then raise Texture_Load_Error with Path & " is not a KTX file"; end if; declare Header : constant Orka.KTX.Header := Orka.KTX.Get_Header (Bytes); Levels : constant GL.Types.Size := GL.Types.Size'Max (1, Header.Mipmap_Levels); Resource : constant Texture_Ptr := new Texture'(others => <>); Texture : GL.Objects.Textures.Texture (Header.Kind); Width : constant GL.Types.Size := Header.Width; Height : GL.Types.Size := Header.Height; Depth : GL.Types.Size := Header.Depth; begin T3 := Clock; -- Allocate storage case Header.Kind is when Texture_2D_Array => Depth := Header.Array_Elements; when Texture_1D_Array => Height := Header.Array_Elements; pragma Assert (Depth = 0); when Texture_Cube_Map_Array => -- For a cube map array, depth is the number of layer-faces Depth := Header.Array_Elements * 6; when Texture_3D => null; when Texture_2D | Texture_Cube_Map => pragma Assert (Depth = 0); when Texture_1D => if Header.Compressed then raise Texture_Load_Error with Path & " has unknown 1D compressed format"; end if; pragma Assert (Height = 0); pragma Assert (Depth = 0); when others => raise Program_Error; end case; if Header.Compressed then Texture.Allocate_Storage (Levels, Header.Compressed_Format, Width, Height, Depth); else Texture.Allocate_Storage (Levels, Header.Internal_Format, Width, Height, Depth); end if; T4 := Clock; -- TODO Handle KTXorientation key value pair -- Upload texture data declare Image_Size_Index : Stream_Element_Offset := Orka.KTX.Get_Data_Offset (Bytes, Header.Bytes_Key_Value); Cube_Map : constant Boolean := Header.Kind = Texture_Cube_Map; begin for Level in 0 .. Levels - 1 loop declare Face_Size : constant Natural := Orka.KTX.Get_Length (Bytes, Image_Size_Index); -- If not Cube_Map, then Face_Size is the size of the whole level Cube_Padding : constant Natural := 3 - ((Face_Size + 3) mod 4); Image_Size : constant Natural := (if Cube_Map then (Face_Size + Cube_Padding) * 6 else Face_Size); -- If Cube_Map then Levels = 1 so no need to add it to the expression -- Compute size of the whole mipmap level Mip_Padding : constant Natural := 3 - ((Image_Size + 3) mod 4); Mipmap_Size : constant Natural := 4 + Image_Size + Mip_Padding; Offset : constant Stream_Element_Offset := Image_Size_Index + 4; pragma Assert (Offset + Stream_Element_Offset (Image_Size) - 1 <= Bytes.Value'Last); Image_Data : constant System.Address := Bytes (Offset)'Address; -- TODO Unpack_Alignment must be 4, but Load_From_Data wants 1 | 2 | 4 -- depending on Header.Data_Type begin case Header.Kind is when Texture_1D => Height := 1; Depth := 1; when Texture_1D_Array | Texture_2D => Depth := 1; when Texture_2D_Array | Texture_3D => null; when Texture_Cube_Map | Texture_Cube_Map_Array => -- Texture_Cube_Map uses 2D storage, but 3D load operation -- according to table 8.15 of the OpenGL specification -- For a cube map, depth is the number of faces, for -- a cube map array, depth is the number of layer-faces Depth := GL.Types.Size'Max (1, Header.Array_Elements) * 6; when others => raise Program_Error; end case; if Header.Compressed then Texture.Load_From_Data (Level, 0, 0, 0, Width, Height, Depth, Header.Compressed_Format, GL.Types.Int (Image_Size), Image_Data); else Texture.Load_From_Data (Level, 0, 0, 0, Width, Height, Depth, Header.Format, Header.Data_Type, Image_Data); end if; Image_Size_Index := Image_Size_Index + Stream_Element_Offset (Mipmap_Size); end; end loop; end; T5 := Clock; -- Generate a full mipmap pyramid if Mipmap_Levels = 0 if Header.Mipmap_Levels = 0 then Texture.Generate_Mipmap; end if; T6 := Clock; Resource.Texture.Replace_Element (Texture); -- Register resource at the resource manager Object.Manager.Add_Resource (Path, Resource_Ptr (Resource)); Messages.Insert (Info, "Loaded texture " & Path & " in " & Logging.Trim (Logging.Image (T6 - T1))); Messages.Insert (Info, " size: " & Logging.Trim (Width'Image) & " x " & Logging.Trim (Height'Image) & " x " & Logging.Trim (Depth'Image) & ", mipmap levels:" & Levels'Image); Messages.Insert (Info, " kind: " & Header.Kind'Image); if Header.Compressed then Messages.Insert (Info, " format: " & Header.Compressed_Format'Image); else Messages.Insert (Info, " format: " & Header.Internal_Format'Image); end if; Messages.Insert (Info, " statistics:"); Messages.Insert (Info, " reading file: " & Logging.Image (T2 - T1)); Messages.Insert (Info, " parsing header: " & Logging.Image (T3 - T2)); Messages.Insert (Info, " storage: " & Logging.Image (T4 - T3)); Messages.Insert (Info, " buffers: " & Logging.Image (T5 - T4)); if Header.Mipmap_Levels = 0 then Messages.Insert (Info, " generating mipmap:" & Logging.Image (T6 - T5)); end if; end; exception when Error : Orka.KTX.Invalid_Enum_Error => declare Message : constant String := Ada.Exceptions.Exception_Message (Error); begin raise Texture_Load_Error with Path & " has " & Message; end; end Execute; ----------------------------------------------------------------------------- -- Loader -- ----------------------------------------------------------------------------- type KTX_Loader is limited new Loaders.Loader with record Manager : Managers.Manager_Ptr; end record; overriding function Extension (Object : KTX_Loader) return Loaders.Extension_String is ("ktx"); overriding procedure Load (Object : KTX_Loader; Data : Loaders.Resource_Data; Enqueue : not null access procedure (Element : Jobs.Job_Ptr); Location : Locations.Location_Ptr) is Job : constant Jobs.Job_Ptr := new KTX_Load_Job' (Jobs.Abstract_Job with Data => Data, Manager => Object.Manager); begin Enqueue (Job); end Load; function Create_Loader (Manager : Managers.Manager_Ptr) return Loaders.Loader_Ptr is (new KTX_Loader'(Manager => Manager)); ----------------------------------------------------------------------------- -- Writer -- ----------------------------------------------------------------------------- procedure Write_Texture (Texture : GL.Objects.Textures.Texture; Location : Locations.Writable_Location_Ptr; Path : String) is package Textures renames GL.Objects.Textures; package Pointers is new Textures.Texture_Pointers (Byte_Pointers); Format : GL.Pixels.Format := GL.Pixels.RGBA; Data_Type : GL.Pixels.Data_Type := GL.Pixels.Float; -- Note: unused if texture is compressed use Ada.Streams; use all type GL.Low_Level.Enums.Texture_Kind; use type GL.Types.Size; Compressed : constant Boolean := Texture.Compressed (0); Header : Orka.KTX.Header (Compressed); function Convert (Bytes : in out GL.Types.UByte_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); procedure Free is new Ada.Unchecked_Deallocation (Object => GL.Types.UByte_Array, Name => GL.Types.UByte_Array_Access); begin for Index in Bytes'Range loop declare Target_Index : constant Stream_Element_Offset := Stream_Element_Offset (Index - Bytes'First + 1); begin Result (Target_Index) := Stream_Element (Bytes (Index)); end; end loop; Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Convert (Bytes : in out Pointers.Element_Array_Access) return Byte_Array_Pointers.Pointer is Pointer : Byte_Array_Pointers.Pointer; Result : constant Byte_Array_Access := new Byte_Array (1 .. Bytes'Length); begin Result.all := Bytes.all; Pointers.Free (Bytes); Pointer.Set (Result); return Pointer; end Convert; function Get_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : Pointers.Element_Array_Access; begin Data := Pointers.Get_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Format, Data_Type); return Convert (Data); end Get_Data; function Get_Compressed_Data (Level : Textures.Mipmap_Level) return Byte_Array_Pointers.Pointer is Data : GL.Types.UByte_Array_Access; begin Data := Textures.Get_Compressed_Data (Texture, Level, 0, 0, 0, Texture.Width (Level), Texture.Height (Level), Texture.Depth (Level), Texture.Compressed_Format (0)); return Convert (Data); end Get_Compressed_Data; begin Header.Kind := Texture.Kind; Header.Width := Texture.Width (0); case Texture.Kind is when Texture_3D => Header.Height := Texture.Height (0); Header.Depth := Texture.Depth (0); when Texture_2D | Texture_2D_Array | Texture_Cube_Map | Texture_Cube_Map_Array => Header.Height := Texture.Height (0); Header.Depth := 0; when Texture_1D | Texture_1D_Array => Header.Height := 0; Header.Depth := 0; when others => raise Program_Error; end case; case Texture.Kind is when Texture_1D_Array => Header.Array_Elements := Texture.Height (0); when Texture_2D_Array => Header.Array_Elements := Texture.Depth (0); when Texture_Cube_Map_Array => Header.Array_Elements := Texture.Depth (0) / 6; when Texture_1D | Texture_2D | Texture_3D | Texture_Cube_Map => Header.Array_Elements := 0; when others => raise Program_Error; end case; Header.Mipmap_Levels := 1; Header.Bytes_Key_Value := 0; if Compressed then Header.Compressed_Format := Texture.Compressed_Format (0); else declare Internal_Format : constant GL.Pixels.Internal_Format := Texture.Internal_Format (0); begin Format := GL.Pixels.Queries.Get_Texture_Format (Internal_Format, Texture.Kind); Data_Type := GL.Pixels.Queries.Get_Texture_Type (Internal_Format, Texture.Kind); Header.Internal_Format := Internal_Format; Header.Format := Format; Header.Data_Type := Data_Type; end; end if; declare Data : constant Byte_Array_Pointers.Pointer := (if Compressed then Get_Compressed_Data (0) else Get_Data (0)); Bytes : constant Byte_Array_Pointers.Pointer := Orka.KTX.Create_KTX_Bytes (Header, Data.Get); begin Location.Write_Data (Path, Bytes.Get); end; end Write_Texture; end Orka.Resources.Textures.KTX;
Simplify debug output of KTX loader a bit
orka: Simplify debug output of KTX loader a bit Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
44abeff207cc321a53a398898b1d515d77117c47
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; if Release then Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Types; with MAT.Memory; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Events.Targets.Event_Id_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; if Release then Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
cfb34ed076510fadf502116f927b60cc14f99d94
src/security-controllers-roles.adb
src/security-controllers-roles.adb
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Serialize.Mappers.Record_Mapper; package body Security.Controllers.Roles is -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. -- ------------------------------ function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then for I in Handler.Roles'Range loop -- if P.Has_Role (Handler.Roles (I)) then return True; -- end if; end loop; end if; return False; end Has_Permission; type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <role> and <role-permission> -- XML entities are found. Create the new permission when the complete permission definition -- has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_ROLE => declare Role : constant String := Util.Beans.Objects.To_String (Value); begin Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role); Into.Count := Into.Count + 1; exception when Permissions.Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role; end; when FIELD_ROLE_PERMISSION => if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Missing at least one role"; end if; declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); Perm : constant Role_Controller_Access := new Role_Controller '(Count => Into.Count, Roles => Into.Roles (1 .. Into.Count)); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; end; when FIELD_ROLE_NAME => declare Name : constant String := Util.Beans.Objects.To_String (Value); Role : Permissions.Role_Type; begin Into.Manager.Add_Role_Type (Name, Role); end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>role-permission</b> description. For example: -- -- <security-role> -- <role-name>admin</role-name> -- </security-role> -- <role-permission> -- <name>create-workspace</name> -- <role>admin</role> -- <role>manager</role> -- </role-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- user has either the <b>admin</b> or the <b>manager</b> role. -- ------------------------------ package body Reader_Config is begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Manager; Config_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; begin Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION); Mapper.Add_Mapping ("role-permission/name", FIELD_NAME); Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE); Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME); end Security.Controllers.Roles;
----------------------------------------------------------------------- -- security-controllers-roles -- Simple role base security -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Security.Controllers.Roles is -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- one of the role defined in the <b>Handler</b>. -- ------------------------------ function Has_Permission (Handler : in Role_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Security.Principal_Access; P : constant Security.Principal_Access := Context.Get_User_Principal; begin if P /= null then for I in Handler.Roles'Range loop -- if P.Has_Role (Handler.Roles (I)) then return True; -- end if; end loop; end if; return False; end Has_Permission; end Security.Controllers.Roles;
Remove the XML configuration reader which is now in Security.Policy.Roles
Remove the XML configuration reader which is now in Security.Policy.Roles
Ada
apache-2.0
stcarrez/ada-security
c7844a1c4e84404b9f376b841873f96bebcad582
src/gen-model-tables.adb
src/gen-model-tables.adb
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; with Util.Log.Loggers; package body Gen.Model.Tables is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables"); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then if Length (From.Sql_Type) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Type); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return T.Get_Value ("name"); end; elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access := null; Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, "."); begin if Pos = 0 then Result := Gen.Model.Mappings.Find_Type (From.Type_Name); end if; if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then Log.Debug ("Found enum"); end if; if Result = null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin -- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); -- if O.Type_Mapping = null then -- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); -- end if; null; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Create a table association with the given name and add it to the table. -- ------------------------------ procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access) is begin Assoc := new Association_Definition; Assoc.Name := Name; Assoc.Number := Table.Members.Get_Count; Assoc.Table := Table'Unchecked_Access; Assoc.Sql_Name := Name; Table.Members.Append (Assoc.all'Access); Table.Has_Associations := True; end Add_Association; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "operations" then return From.Operations_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Util.Strings; with Util.Log.Loggers; package body Gen.Model.Tables is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Tables"); -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object is use type Gen.Model.Mappings.Mapping_Definition_Access; begin if Name = "type" then declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return Util.Beans.Objects.To_Object (T.all'Access, Util.Beans.Objects.STATIC); end; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "index" then return Util.Beans.Objects.To_Object (From.Number); elsif Name = "isUnique" then return Util.Beans.Objects.To_Object (From.Unique); elsif Name = "isNull" then return Util.Beans.Objects.To_Object (not From.Not_Null); elsif Name = "isInserted" then return Util.Beans.Objects.To_Object (From.Is_Inserted); elsif Name = "isUpdated" then return Util.Beans.Objects.To_Object (From.Is_Updated); elsif Name = "sqlType" then if Length (From.Sql_Type) > 0 then return Util.Beans.Objects.To_Object (From.Sql_Type); end if; declare T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T = null then return Util.Beans.Objects.Null_Object; end if; return T.Get_Value ("name"); end; elsif Name = "sqlName" then return Util.Beans.Objects.To_Object (From.Sql_Name); elsif Name = "isVersion" then return Util.Beans.Objects.To_Object (From.Is_Version); elsif Name = "isReadable" then return Util.Beans.Objects.To_Object (From.Is_Readable); elsif Name = "isPrimaryKey" then return Util.Beans.Objects.To_Object (From.Is_Key); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Is_Basic_Type); elsif Name = "generator" then return From.Generator; else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Returns true if the column type is a basic type. -- ------------------------------ function Is_Basic_Type (From : in Column_Definition) return Boolean is use type Gen.Model.Mappings.Mapping_Definition_Access; use type Gen.Model.Mappings.Basic_Type; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; Name : constant String := To_String (From.Type_Name); begin if T /= null then return T.Kind /= Gen.Model.Mappings.T_BLOB; end if; return Name = "int" or Name = "String" or Name = "ADO.Identifier" or Name = "Timestamp" or Name = "Integer" or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time"; end Is_Basic_Type; -- ------------------------------ -- Returns the column type. -- ------------------------------ function Get_Type (From : in Column_Definition) return String is use type Gen.Model.Mappings.Mapping_Definition_Access; T : constant Gen.Model.Mappings.Mapping_Definition_Access := From.Get_Type_Mapping; begin if T /= null then return To_String (T.Target); else return To_String (From.Type_Name); end if; end Get_Type; -- ------------------------------ -- Returns the column type mapping. -- ------------------------------ function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access is use type Mappings.Mapping_Definition_Access; Result : Gen.Model.Mappings.Mapping_Definition_Access := null; Pos : constant Natural := Ada.Strings.Unbounded.Index (From.Type_Name, "."); begin if Pos = 0 then Result := Gen.Model.Mappings.Find_Type (From.Type_Name); end if; if From.Type_Name = "Gen.Tests.Tables.Test_Enum" then Log.Debug ("Found enum"); end if; if Result = null then Result := From.Table.Package_Def.Find_Type (From.Type_Name); end if; return Result; end Get_Type_Mapping; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Column_Definition) is use type Mappings.Mapping_Definition_Access; begin -- O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name); -- if O.Type_Mapping = null then -- O.Type_Mapping := O.Table.Package_Def.Find_Type (O.Type_Name); -- end if; null; end Prepare; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object is begin return Column_Definition (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Table_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); O.Operations_Bean := Util.Beans.Objects.To_Object (O.Operations'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is Table : constant Table_Definition_Access := new Table_Definition; begin Table.Name := Name; Table.Kind := Gen.Model.Mappings.T_TABLE; declare Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1); Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; Table.Table_Name := Table.Type_Name; end; return Table; end Create_Table; -- ------------------------------ -- Create a table column with the given name and add it to the table. -- ------------------------------ procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access) is begin Column := new Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Table.Members.Get_Count; Column.Table := Table'Unchecked_Access; Table.Members.Append (Column); if Name = "version" then Table.Version_Column := Column; Column.Is_Version := True; Column.Is_Updated := False; Column.Is_Inserted := False; elsif Name = "id" then Table.Id_Column := Column; Column.Is_Key := True; end if; end Add_Column; -- ------------------------------ -- Create a table association with the given name and add it to the table. -- ------------------------------ procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access) is begin Assoc := new Association_Definition; Assoc.Name := Name; Assoc.Number := Table.Members.Get_Count; Assoc.Table := Table'Unchecked_Access; Assoc.Sql_Name := Name; Table.Members.Append (Assoc.all'Access); Table.Has_Associations := True; end Add_Association; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Table_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "operations" then return From.Operations_Bean; elsif Name = "id" and From.Id_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "version" and From.Version_Column /= null then declare Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Version_Column.all'Unchecked_Access; begin return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC); end; elsif Name = "hasAssociations" then return Util.Beans.Objects.To_Object (From.Has_Associations); elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "table" then return Util.Beans.Objects.To_Object (From.Table_Name); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Table_Definition) is Iter : Column_List.Cursor := O.Members.First; begin while Column_List.Has_Element (Iter) loop Column_List.Element (Iter).Prepare; Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Set the table name and determines the package name. -- ------------------------------ procedure Set_Table_Name (Table : in out Table_Definition; Name : in String) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin Table.Name := To_Unbounded_String (Name); if Pos > 0 then Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1)); Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last)); else Table.Pkg_Name := To_Unbounded_String ("ADO"); Table.Type_Name := Table.Name; end if; end Set_Table_Name; end Gen.Model.Tables;
Mark the table type mapping as a T_TABLE
Mark the table type mapping as a T_TABLE
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
37386f983fd1e9c8331e1f0853a573094c41d8aa
matp/src/mat-expressions.ads
matp/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events.Targets; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Create an event ID range expression node. function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type; -- Create a thread ID range expression node. function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type; -- Create a event type expression check. function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_EVENT, N_CONDITION, N_THREAD, N_TYPE); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Min_Thread : MAT.Types.Target_Thread_Ref; Max_Thread : MAT.Types.Target_Thread_Ref; when N_EVENT => Min_Event : MAT.Events.Targets.Event_Id_Type; Max_Event : MAT.Events.Targets.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.Targets.Probe_Index_Type; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Finalization; private with Util.Concurrent.Counters; with MAT.Types; with MAT.Memory; with MAT.Events.Targets; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Inside_Type is (INSIDE_FILE, INSIDE_DIRECT_FILE, INSIDE_FUNCTION, INSIDE_DIRECT_FUNCTION); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a AND expression node. function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create a OR expression node. function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type; -- Create an INSIDE expression node. function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type; -- Create an size range expression node. function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type; -- Create an addr range expression node. function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type; -- Create an time range expression node. function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type; -- Create an event ID range expression node. function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type; -- Create a thread ID range expression node. function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type; -- Create a event type expression check. function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; -- Parse the string and return the expression tree. function Parse (Expr : in String) return Expression_Type; -- Empty expression. EMPTY : constant Expression_Type; type yystype is record low : MAT.Types.Uint64 := 0; high : MAT.Types.Uint64 := 0; bval : Boolean := False; name : Ada.Strings.Unbounded.Unbounded_String; expr : Expression_Type; end record; private type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_RANGE_TIME, N_EVENT, N_CONDITION, N_THREAD, N_TYPE); type Node_Type; type Node_Type_Access is access all Node_Type; type Node_Type (Kind : Kind_Type) is record Ref_Counter : Util.Concurrent.Counters.Counter; case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; Inside : Inside_Type; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_RANGE_TIME => Min_Time : MAT.Types.Target_Tick_Ref; Max_Time : MAT.Types.Target_Tick_Ref; when N_THREAD => Min_Thread : MAT.Types.Target_Thread_Ref; Max_Thread : MAT.Types.Target_Thread_Ref; when N_EVENT => Min_Event : MAT.Events.Targets.Event_Id_Type; Max_Event : MAT.Events.Targets.Event_Id_Type; when N_TYPE => Event_Kind : MAT.Events.Targets.Probe_Index_Type; when others => null; end case; end record; -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean; -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean; type Expression_Type is new Ada.Finalization.Controlled with record Node : Node_Type_Access; end record; -- Release the reference and destroy the expression tree if it was the last reference. overriding procedure Finalize (Obj : in out Expression_Type); -- Update the reference after an assignment. overriding procedure Adjust (Obj : in out Expression_Type); -- Empty expression. EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with Node => null); end MAT.Expressions;
Declare yystype in the MAT.Expressions package to solve some elaboration order issue raised by gcc 4.9
Declare yystype in the MAT.Expressions package to solve some elaboration order issue raised by gcc 4.9
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
390803ddfc6121e5af168053c4287865cc26ab35
regtests/util-processes-tests.ads
regtests/util-processes-tests.ads
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Processes.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Tests when the process is not launched procedure Test_No_Process (T : in out Test); -- Test executing a process procedure Test_Spawn (T : in out Test); -- Test output pipe redirection: read the process standard output procedure Test_Output_Pipe (T : in out Test); -- Test input pipe redirection: write the process standard input procedure Test_Input_Pipe (T : in out Test); -- Test shell splitting. procedure Test_Shell_Splitting_Pipe (T : in out Test); -- Test launching several processes through pipes in several threads. procedure Test_Multi_Spawn (T : in out Test); -- Test output file redirection. procedure Test_Output_Redirect (T : in out Test); end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Processes.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Tests when the process is not launched procedure Test_No_Process (T : in out Test); -- Test executing a process procedure Test_Spawn (T : in out Test); -- Test output pipe redirection: read the process standard output procedure Test_Output_Pipe (T : in out Test); -- Test input pipe redirection: write the process standard input procedure Test_Input_Pipe (T : in out Test); -- Test shell splitting. procedure Test_Shell_Splitting_Pipe (T : in out Test); -- Test launching several processes through pipes in several threads. procedure Test_Multi_Spawn (T : in out Test); -- Test output file redirection. procedure Test_Output_Redirect (T : in out Test); -- Test the Tools.Execute operation. procedure Test_Tools_Execute (T : in out Test); end Util.Processes.Tests;
Declare the Test_Tools_Execute procedure
Declare the Test_Tools_Execute procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4456feeaac2f0ef14a029cd5235bb46054005dd1
mat/src/mat-expressions.ads
mat/src/mat-expressions.ads
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_CONDITION, N_THREAD); type Expression_Type is tagged private; -- Create a new expression node. function Create (Kindx : in Kind_Type; Expr : in Expression_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type; type Node_Type_Access is access all Node_Type'Class; type Node_Type (Kind : Kind_Type) is tagged limited record case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Refs; with MAT.Types; with MAT.Memory; package MAT.Expressions is type Context_Type is record Addr : MAT.Types.Target_Addr; Allocation : MAT.Memory.Allocation; end record; type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE, N_IN_FILE, N_IN_FILE_DIRECT, N_CALL_ADDR, N_CALL_ADDR_DIRECT, N_IN_FUNC, N_IN_FUNC_DIRECT, N_RANGE_SIZE, N_RANGE_ADDR, N_CONDITION, N_THREAD); type Expression_Type is tagged private; -- Create a NOT expression node. function Create_Not (Expr : in Expression_Type) return Expression_Type; -- Create a new expression node. function Create (Kindx : in Kind_Type; Expr : in Expression_Type) return Expression_Type; -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. function Is_Selected (Node : in Expression_Type; Context : in Context_Type) return Boolean; private type Node_Type; type Node_Type_Access is access all Node_Type'Class; type Node_Type (Kind : Kind_Type) is new Util.Refs.Ref_Entity with record case Kind is when N_NOT => Expr : Node_Type_Access; when N_OR | N_AND => Left, Right : Node_Type_Access; when N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT => Name : Ada.Strings.Unbounded.Unbounded_String; when N_RANGE_SIZE => Min_Size : MAT.Types.Target_Size; Max_Size : MAT.Types.Target_Size; when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT => Min_Addr : MAT.Types.Target_Addr; Max_Addr : MAT.Types.Target_Addr; when N_THREAD => Thread : MAT.Types.Target_Thread_Ref; when others => null; end case; end record; function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean; type Expression_Type is tagged record Node : Node_Type_Access; end record; end MAT.Expressions;
Use Util.Refs for the reference counting New function Create_Not to create a not expression
Use Util.Refs for the reference counting New function Create_Not to create a not expression
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a307fd53bf3d8a27f9db52d3b91dfe0e1c6ef7b5
src/asf-contexts-facelets.ads
src/asf-contexts-facelets.ads
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- 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.Strings; with EL.Objects; with EL.Contexts; with EL.Expressions; with EL.Functions; with ASF.Components.Base; with ASF.Converters; with ASF.Validators; with Ada.Strings.Unbounded; with Ada.Containers.Vectors; limited with ASF.Applications.Main; limited with ASF.Views.Nodes.Facelets; package ASF.Contexts.Facelets is use ASF.Components; use Ada.Strings.Unbounded; -- ------------------------------ -- Facelet context -- ------------------------------ -- The <b>Facelet_Context</b> defines a context used exclusively when -- building the component tree from the facelet nodes. It allows to -- compose the component tree by using other facelet fragments. type Facelet_Context is abstract tagged private; type Facelet_Context_Access is access all Facelet_Context'Class; -- Get the EL context for evaluating expressions. function Get_ELContext (Context : in Facelet_Context) return EL.Contexts.ELContext_Access; -- Set the EL context for evaluating expressions. procedure Set_ELContext (Context : in out Facelet_Context; ELContext : in EL.Contexts.ELContext_Access); -- Get the function mapper associated with the EL context. function Get_Function_Mapper (Context : in Facelet_Context) return EL.Functions.Function_Mapper_Access; -- Set the attribute having given name with the value. procedure Set_Attribute (Context : in out Facelet_Context; Name : in String; Value : in EL.Objects.Object); -- Set the attribute having given name with the value. procedure Set_Attribute (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Expressions.Expression); -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in String; Value : in EL.Expressions.Expression); -- Include the facelet from the given source file. -- The included views appended to the parent component tree. procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Include the definition having the given name. procedure Include_Definition (Context : in out Facelet_Context; Name : in Unbounded_String; Parent : in Base.UIComponent_Access; Found : out Boolean); -- Push into the current facelet context the <ui:define> nodes contained in -- the composition/decorate tag. procedure Push_Defines (Context : in out Facelet_Context; Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node); -- Pop from the current facelet context the <ui:define> nodes. procedure Pop_Defines (Context : in out Facelet_Context); -- Set the path to resolve relative facelet paths and get the previous path. procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in String; Previous : out Unbounded_String); -- Set the path to resolve relative facelet paths. procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in Unbounded_String); -- Resolve the facelet relative path function Resolve_Path (Context : Facelet_Context; Path : String) return String; -- Get a converter from a name. -- Returns the converter object or null if there is no converter. function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Get a validator from a name. -- Returns the validator object or null if there is no validator. function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Get the application associated with this facelet context. function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is abstract; private type Composition_Tag_Node is access all ASF.Views.Nodes.Facelets.Composition_Tag_Node'Class; package Defines_Vector is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Composition_Tag_Node); type Facelet_Context is abstract tagged record -- The expression context; Context : EL.Contexts.ELContext_Access := null; Defines : Defines_Vector.Vector; Path : Unbounded_String; Inserts : Util.Strings.String_Set.Set; -- The application Application : access ASF.Applications.Main.Application'Class; end record; end ASF.Contexts.Facelets;
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with EL.Objects; with EL.Contexts; with EL.Expressions; with EL.Functions; with ASF.Components.Base; with ASF.Converters; with ASF.Validators; with Ada.Strings.Unbounded; with Ada.Containers.Vectors; limited with ASF.Views.Nodes.Facelets; package ASF.Contexts.Facelets is use ASF.Components; use Ada.Strings.Unbounded; -- ------------------------------ -- Facelet context -- ------------------------------ -- The <b>Facelet_Context</b> defines a context used exclusively when -- building the component tree from the facelet nodes. It allows to -- compose the component tree by using other facelet fragments. type Facelet_Context is abstract tagged private; type Facelet_Context_Access is access all Facelet_Context'Class; -- Get the EL context for evaluating expressions. function Get_ELContext (Context : in Facelet_Context) return EL.Contexts.ELContext_Access; -- Set the EL context for evaluating expressions. procedure Set_ELContext (Context : in out Facelet_Context; ELContext : in EL.Contexts.ELContext_Access); -- Get the function mapper associated with the EL context. function Get_Function_Mapper (Context : in Facelet_Context) return EL.Functions.Function_Mapper_Access; -- Set the attribute having given name with the value. procedure Set_Attribute (Context : in out Facelet_Context; Name : in String; Value : in EL.Objects.Object); -- Set the attribute having given name with the value. procedure Set_Attribute (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Expressions.Expression); -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in String; Value : in EL.Expressions.Expression); -- Include the facelet from the given source file. -- The included views appended to the parent component tree. procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Include the definition having the given name. procedure Include_Definition (Context : in out Facelet_Context; Name : in Unbounded_String; Parent : in Base.UIComponent_Access; Found : out Boolean); -- Push into the current facelet context the <ui:define> nodes contained in -- the composition/decorate tag. procedure Push_Defines (Context : in out Facelet_Context; Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node); -- Pop from the current facelet context the <ui:define> nodes. procedure Pop_Defines (Context : in out Facelet_Context); -- Set the path to resolve relative facelet paths and get the previous path. procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in String; Previous : out Unbounded_String); -- Set the path to resolve relative facelet paths. procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in Unbounded_String); -- Resolve the facelet relative path function Resolve_Path (Context : Facelet_Context; Path : String) return String; -- Get a converter from a name. -- Returns the converter object or null if there is no converter. function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is abstract; -- Get a validator from a name. -- Returns the validator object or null if there is no validator. function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is abstract; private type Composition_Tag_Node is access all ASF.Views.Nodes.Facelets.Composition_Tag_Node'Class; package Defines_Vector is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Composition_Tag_Node); type Facelet_Context is abstract tagged record -- The expression context; Context : EL.Contexts.ELContext_Access := null; Defines : Defines_Vector.Vector; Path : Unbounded_String; Inserts : Util.Strings.String_Set.Set; end record; end ASF.Contexts.Facelets;
Change Get_Converter and Get_Validator to abstract functions and remove the Get_Application and the 'limited with' clause for the Applications.Main package
Change Get_Converter and Get_Validator to abstract functions and remove the Get_Application and the 'limited with' clause for the Applications.Main package
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
843283e89124cc6d6f3e22fca0dc9267a4c3d2f5
src/base/files/util-files.ads
src/base/files/util-files.ads
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 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.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; -- = Files = -- The `Util.Files` package provides various utility operations arround files -- to help in reading, writing, searching for files in a path. -- To use the operations described here, use the following GNAT project: -- -- with "utilada_base"; -- -- == Reading and writing == -- To easily get the full content of a file, the `Read_File` procedure can be -- used. A first form exists that populates a `Unbounded_String` or a vector -- of strings. A second form exists with a procedure that is called with each -- line while the file is read. These different forms simplify the reading of -- files as it is possible to write: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- Util.Files.Read_File ("config.txt", Content); -- -- or -- -- List : Util.Strings.Vectors.Vector; -- Util.Files.Read_File ("config.txt", List); -- -- or -- -- procedure Read_Line (Line : in String) is ... -- Util.Files.Read_File ("config.txt", Read_Line'Access); -- -- Similarly, writing a file when you have a string or an `Unbounded_String` -- is easily written by using `Write_File` as follows: -- -- Util.Files.Write_File ("config.txt", "full content"); -- -- == Searching files == -- Searching for a file in a list of directories can be accomplished by using -- the `Iterate_Path`, `Iterate_Files_Path` or `Find_File_Path`. -- -- The `Find_File_Path` function is helpful to find a file in some `PATH` -- search list. The function looks in each search directory for the given -- file name and it builds and returns the computed path of the first file -- found in the search list. For example: -- -- Path : String := Util.Files.Find_File_Path ("ls", -- "/bin:/usr/bin", -- ':'); -- -- This will return `/usr/bin/ls` on most Unix systems. -- -- @include util-files-rolling.ads package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. function Find_File_Path (Name : in String; Paths : in String; Separator : in Character := ';') return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; -- Rename the old name into a new name. procedure Rename (Old_Name, New_Name : in String); -- Delete the file including missing symbolic link -- or socket files (which GNAT fails to delete, -- see gcc/63222 and gcc/56055). procedure Delete_File (Path : in String); end Util.Files;
----------------------------------------------------------------------- -- util-files -- Various File Utility Packages -- Copyright (C) 2001 - 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.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; -- = Files = -- The `Util.Files` package provides various utility operations arround files -- to help in reading, writing, searching for files in a path. -- To use the operations described here, use the following GNAT project: -- -- with "utilada_base"; -- -- == Reading and writing == -- To easily get the full content of a file, the `Read_File` procedure can be -- used. A first form exists that populates a `Unbounded_String` or a vector -- of strings. A second form exists with a procedure that is called with each -- line while the file is read. These different forms simplify the reading of -- files as it is possible to write: -- -- Content : Ada.Strings.Unbounded.Unbounded_String; -- Util.Files.Read_File ("config.txt", Content); -- -- or -- -- List : Util.Strings.Vectors.Vector; -- Util.Files.Read_File ("config.txt", List); -- -- or -- -- procedure Read_Line (Line : in String) is ... -- Util.Files.Read_File ("config.txt", Read_Line'Access); -- -- Similarly, writing a file when you have a string or an `Unbounded_String` -- is easily written by using `Write_File` as follows: -- -- Util.Files.Write_File ("config.txt", "full content"); -- -- == Searching files == -- Searching for a file in a list of directories can be accomplished by using -- the `Iterate_Path`, `Iterate_Files_Path` or `Find_File_Path`. -- -- The `Find_File_Path` function is helpful to find a file in some `PATH` -- search list. The function looks in each search directory for the given -- file name and it builds and returns the computed path of the first file -- found in the search list. For example: -- -- Path : String := Util.Files.Find_File_Path ("ls", -- "/bin:/usr/bin", -- ':'); -- -- This will return `/usr/bin/ls` on most Unix systems. -- -- @include util-files-rolling.ads package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file `Name` in one of the search directories defined in `Paths`. -- Each search directory is separated by ';' by default (yes, even on Unix). -- This can be changed by specifying the `Separator` value. -- Returns the path to be used for reading the file. function Find_File_Path (Name : in String; Paths : in String; Separator : in Character := ';') return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';' (this can be overriding with the `Separator` parameter). -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String; Separator : in Character := ';') return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; -- Rename the old name into a new name. procedure Rename (Old_Name, New_Name : in String); -- Delete the file including missing symbolic link -- or socket files (which GNAT fails to delete, -- see gcc/63222 and gcc/56055). The function returns 0 -- or the system error code. The procedure raises the Use_Error -- exception if the file cannot be deleted. function Delete_File (Path : in String) return Integer; procedure Delete_File (Path : in String); -- Delete the directory tree recursively. If the directory tree contains -- sockets, special files and dangling symbolic links, they are removed -- correctly. This is a workarround for GNAT bug gcc/63222 and gcc/56055. procedure Delete_Tree (Path : in String); end Util.Files;
Declare the Delete_Tree procedure to solve a bug in gcc in Ada.Directories.Delete_Tree
Declare the Delete_Tree procedure to solve a bug in gcc in Ada.Directories.Delete_Tree
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0fece7078de1156024c04a3a9d3f39a177e97ead
src/orka/implementation/orka-terminals.adb
src/orka/implementation/orka-terminals.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Calendar.Formatting; with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Ada.Text_IO; with Orka.OS; with Orka.Strings; package body Orka.Terminals is Style_Codes : constant array (Style) of Natural := (Default => 0, Bold => 1, Dark => 2, Italic => 3, Underline => 4, Blink => 5, Reversed => 7, Cross_Out => 9); Foreground_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 30, Red => 31, Green => 32, Yellow => 33, Blue => 34, Magenta => 35, Cyan => 36, White => 37); Background_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 40, Red => 41, Green => 42, Yellow => 43, Blue => 44, Magenta => 45, Cyan => 46, White => 47); package L renames Ada.Characters.Latin_1; package SF renames Ada.Strings.Fixed; Reset : constant String := L.ESC & "[0m"; function Sequence (Code : Natural) return String is Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both); begin return (if Code /= 0 then L.ESC & "[" & Image & "m" else ""); end Sequence; function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String is FG : constant String := Sequence (Foreground_Color_Codes (Foreground)); BG : constant String := Sequence (Background_Color_Codes (Background)); ST : constant String := Sequence (Style_Codes (Attribute)); begin return Reset & FG & BG & ST & Text & Reset; end Colorize; ----------------------------------------------------------------------------- Time_Zero : constant Duration := Orka.OS.Monotonic_Clock; function Time_Image return String is use Ada.Calendar.Formatting; Hour : Hour_Number; Minute : Minute_Number; Second : Second_Number; Sub_Second : Second_Duration; Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero; Days_Since_Zero : Natural := 0; begin while Seconds_Since_Zero > Ada.Calendar.Day_Duration'Last loop Seconds_Since_Zero := Seconds_Since_Zero - Ada.Calendar.Day_Duration'Last; Days_Since_Zero := Days_Since_Zero + 1; end loop; Split (Seconds_Since_Zero, Hour, Minute, Second, Sub_Second); declare -- Remove first character (space) from ' hhmmss' image and then pad it to six digits Image1 : constant String := Natural'Image ((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second); Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0'); -- Insert ':' characters to get 'hh:mm:ss' Image3 : constant String := SF.Insert (Image2, 5, ":"); Image4 : constant String := SF.Insert (Image3, 3, ":"); -- Take image without first character (space) and then pad it to six digits Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6)); Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0'); begin return Image4 & "." & Image6; end; end Time_Image; package Duration_IO is new Ada.Text_IO.Fixed_IO (Duration); type String_Access is not null access String; Suffices : constant array (1 .. 3) of String_Access := (new String'("s"), new String'("ms"), new String'("us")); Last_Suffix : constant String_Access := Suffices (Suffices'Last); function Image (Value : Duration) return String is Result : String := "-9999.999"; Number : Duration := Value; Suffix : String_Access := Suffices (Suffices'First); begin for S of Suffices loop Suffix := S; exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix; Number := Number * 1e3; end loop; begin Duration_IO.Put (Result, Item => Number, Aft => 3); exception when others => return Number'Image & " " & Suffix.all; end; return Result & " " & Suffix.all; end Image; function Trim (Value : String) return String renames Orka.Strings.Trim; function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term; end Orka.Terminals;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Characters.Latin_1; with Ada.Strings.Fixed; with Ada.Text_IO; with Orka.OS; with Orka.Strings; package body Orka.Terminals is Style_Codes : constant array (Style) of Natural := (Default => 0, Bold => 1, Dark => 2, Italic => 3, Underline => 4, Blink => 5, Reversed => 7, Cross_Out => 9); Foreground_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 30, Red => 31, Green => 32, Yellow => 33, Blue => 34, Magenta => 35, Cyan => 36, White => 37); Background_Color_Codes : constant array (Color) of Natural := (Default => 0, Grey => 40, Red => 41, Green => 42, Yellow => 43, Blue => 44, Magenta => 45, Cyan => 46, White => 47); package L renames Ada.Characters.Latin_1; package SF renames Ada.Strings.Fixed; Reset : constant String := L.ESC & "[0m"; function Sequence (Code : Natural) return String is Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both); begin return (if Code /= 0 then L.ESC & "[" & Image & "m" else ""); end Sequence; function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String is FG : constant String := Sequence (Foreground_Color_Codes (Foreground)); BG : constant String := Sequence (Background_Color_Codes (Background)); ST : constant String := Sequence (Style_Codes (Attribute)); begin return Reset & FG & BG & ST & Text & Reset; end Colorize; ----------------------------------------------------------------------------- Time_Zero : constant Duration := Orka.OS.Monotonic_Clock; Day_In_Seconds : constant := 24.0 * 60.0 * 60.0; function Time_Image return String is Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero; Days_Since_Zero : Natural := 0; begin while Seconds_Since_Zero > Day_In_Seconds loop Seconds_Since_Zero := Seconds_Since_Zero - Day_In_Seconds; Days_Since_Zero := Days_Since_Zero + 1; end loop; declare Seconds_Rounded : constant Natural := Natural (Duration'Max (0.0, Seconds_Since_Zero - 0.5)); Hour : constant Natural := Seconds_Rounded / 3600; Minute : constant Natural := (Seconds_Rounded mod 3600) / 60; Second : constant Natural := Seconds_Rounded mod 60; Sub_Second : constant Duration := Seconds_Since_Zero - Duration (Hour * 3600 + Minute * 60 + Second); -- Remove first character (space) from ' hhmmss' image and then pad it to six digits Image1 : constant String := Natural'Image ((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second); Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0'); -- Insert ':' characters to get 'hh:mm:ss' Image3 : constant String := SF.Insert (Image2, 5, ":"); Image4 : constant String := SF.Insert (Image3, 3, ":"); -- Take image without first character (space) and then pad it to six digits Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6)); Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0'); begin return Image4 & "." & Image6; end; end Time_Image; package Duration_IO is new Ada.Text_IO.Fixed_IO (Duration); type String_Access is not null access String; Suffices : constant array (1 .. 3) of String_Access := (new String'("s"), new String'("ms"), new String'("us")); Last_Suffix : constant String_Access := Suffices (Suffices'Last); function Image (Value : Duration) return String is Result : String := "-9999.999"; Number : Duration := Value; Suffix : String_Access := Suffices (Suffices'First); begin for S of Suffices loop Suffix := S; exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix; Number := Number * 1e3; end loop; begin Duration_IO.Put (Result, Item => Number, Aft => 3); exception when others => return Number'Image & " " & Suffix.all; end; return Result & " " & Suffix.all; end Image; function Trim (Value : String) return String renames Orka.Strings.Trim; function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term; end Orka.Terminals;
Replace Split in function Time_Image with an own implementation
orka: Replace Split in function Time_Image with an own implementation The duration is always greater than or equal to zero because of the monotonic clock. Durations around 24 hours and 100 hours have been tested as well. One step closer to pragma Preelaborate ;) Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
c17d21cffaaafc9ed987d2a506ae66db9c7c3cca
mat/src/frames/mat-frames.adb
mat/src/frames/mat-frames.adb
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Interfaces; use Interfaces; with MAT.Types; use MAT.Types; package body MAT.Frames is procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- Create a root for stack frame representation. function Create_Root return Frame_Ptr is begin return new Frame; end Create_Root; -- Destroy the frame tree recursively. procedure Destroy (Tree : in out Frame_Ptr) is F : Frame_Ptr; begin -- Destroy its children recursively. while Tree.Children /= null loop F := Tree.Children; Destroy (F); end loop; -- Unlink from parent list. if Tree.Parent /= null then F := Tree.Parent.Children; if F = Tree then Tree.Parent.Children := Tree.Next; else while F /= null and F.Next /= Tree loop F := F.Next; end loop; if F = null then raise Program_Error; end if; F.Next := Tree.Next; end if; end if; Free (Tree); end Destroy; -- Release the frame when its reference is no longer necessary. procedure Release (F : in Frame_Ptr) is Current : Frame_Ptr := F; begin -- Scan the fram until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Ptr := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; end Release; -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. procedure Split (F : in out Frame_Ptr; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Ptr := F.Parent.Children; begin -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; end Split; procedure Add_Frame (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; end loop; Result := Child; end Add_Frame; procedure Insert (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Current : Frame_Ptr := F; Child : Frame_Ptr; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current := Child; Lpos := 2; Pos := Pos + 1; Current.Used := Current.Used + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is Child : Frame_Ptr := F.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (F : in Frame_Ptr; Pc : in PC_Table; Result : out Frame_Ptr; Last_Pc : out Natural) is Current : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search: while Pos <= Pc'Last loop declare Addr : Target_Addr := Pc (Pos); Child : Frame_Ptr := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Interfaces; use Interfaces; with MAT.Types; use MAT.Types; package body MAT.Frames is procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- Destroy the frame tree recursively. procedure Destroy (Tree : in out Frame_Ptr) is F : Frame_Ptr; begin -- Destroy its children recursively. while Tree.Children /= null loop F := Tree.Children; Destroy (F); end loop; -- Unlink from parent list. if Tree.Parent /= null then F := Tree.Parent.Children; if F = Tree then Tree.Parent.Children := Tree.Next; else while F /= null and F.Next /= Tree loop F := F.Next; end loop; if F = null then raise Program_Error; end if; F.Next := Tree.Next; end if; end if; Free (Tree); end Destroy; -- Release the frame when its reference is no longer necessary. procedure Release (F : in Frame_Ptr) is Current : Frame_Ptr := F; begin -- Scan the fram until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Ptr := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; end Release; -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. procedure Split (F : in out Frame_Ptr; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Ptr := F.Parent.Children; begin -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; end Split; procedure Add_Frame (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; end loop; Result := Child; end Add_Frame; procedure Insert (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr) is Current : Frame_Ptr := F; Child : Frame_Ptr; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current := Child; Lpos := 2; Pos := Pos + 1; Current.Used := Current.Used + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is Child : Frame_Ptr := F.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is Child : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (F : in Frame_Ptr; Pc : in PC_Table; Result : out Frame_Ptr; Last_Pc : out Natural) is Current : Frame_Ptr := F; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search: while Pos <= Pc'Last loop declare Addr : Target_Addr := Pc (Pos); Child : Frame_Ptr := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
Refactor Create_Root operation
Refactor Create_Root operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a337b20dca35213bf85a268278531ac5b6f96629
src/miscellaneous/spatial_data.ads
src/miscellaneous/spatial_data.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with CommonText; package Spatial_Data is package CT renames CommonText; type Collection_Type is (unset, single_point, single_line_string, single_polygon, multi_point, multi_line_string, multi_polygon, heterogeneous); type Geometric_Shape is (point_shape, line_string_shape, polygon_shape, mixture); -- The range limits are necessary to avoid storage error warnings subtype Geo_Points is Positive range 1 .. 2 ** 20; subtype Geo_Units is Natural range 0 .. 2 ** 12; -- Mutable variant records must be limited if tagged -- However, limited geometry cannot work. We must be able to change the -- contents discriminate, so it meants this record cannot be tagged. type Geometry (contents : Collection_Type := unset; units : Geo_Units := Geo_Units'First; subunits : Geo_Units := Geo_Units'First; points : Geo_Points := Geo_Points'First) is private; type Geometric_Real is digits 18; type Geometric_Point is record X : Geometric_Real; Y : Geometric_Real; end record; type Geometric_Circle is record center_point : Geometric_Point; radius : Geometric_Real; end record; type Slope_Intercept is record slope : Geometric_Real; y_intercept : Geometric_Real; vertical : Boolean; end record; type Standard_Form is record A : Geometric_Real; B : Geometric_Real; C : Geometric_Real; end record; type Geometric_Point_set is array (Positive range <>) of Geometric_Point; subtype Geometric_Ring is Geometric_Point_set; subtype Geometric_Line_String is Geometric_Point_set; subtype Geometric_Line is Geometric_Line_String (1 .. 2); type Geometric_Polygon (rings : Geo_Units := Geo_Units'First; points : Geo_Points := Geo_Points'First) is private; Origin_Point : constant Geometric_Point := (0.0, 0.0); -------------------------------- -- Initialization functions -- -------------------------------- function start_polygon (outer_ring : Geometric_Ring) return Geometric_Polygon; procedure append_inner_ring (polygon : in out Geometric_Polygon; inner_ring : Geometric_Ring); function initialize_as_point (point : Geometric_Point) return Geometry; function initialize_as_multi_point (point : Geometric_Point) return Geometry; function initialize_as_line (line_string : Geometric_Line_String) return Geometry; function initialize_as_multi_line (line_string : Geometric_Line_String) return Geometry; function initialize_as_polygon (polygon : Geometric_Polygon) return Geometry; function initialize_as_multi_polygon (polygon : Geometric_Polygon) return Geometry; function initialize_as_collection (anything : Geometry) return Geometry; ----------------------------------- -- Build collections functions -- ----------------------------------- procedure augment_multi_point (collection : in out Geometry; point : Geometric_Point); procedure augment_multi_line (collection : in out Geometry; line : Geometric_Line_String); procedure augment_multi_polygon (collection : in out Geometry; polygon : Geometric_Polygon); procedure augment_collection (collection : in out Geometry; anything : Geometry); --------------------------- -- Retrieval functions -- --------------------------- function type_of_collection (collection : Geometry) return Collection_Type; function size_of_collection (collection : Geometry) return Positive; function collection_item_shape (collection : Geometry; index : Positive := 1) return Geometric_Shape; function collection_item_type (collection : Geometry; index : Positive := 1) return Collection_Type; function retrieve_subcollection (collection : Geometry; index : Positive := 1) return Geometry; function retrieve_point (collection : Geometry; index : Positive := 1) return Geometric_Point; function retrieve_line (collection : Geometry; index : Positive := 1) return Geometric_Line_String; function retrieve_polygon (collection : Geometry; index : Positive := 1) return Geometric_Polygon; function number_of_rings (polygon : Geometric_Polygon) return Natural; function retrieve_ring (polygon : Geometric_Polygon; ring_index : Positive) return Geometric_Ring; ------------------- -- Conversions -- ------------------- function convert_infinite_line (line : Geometric_Line) return Slope_Intercept; function convert_infinite_line (line : Geometric_Line) return Standard_Form; function convert_to_infinite_line (std_form : Standard_Form) return Geometric_Line; function convert_to_infinite_line (intercept_form : Slope_Intercept) return Geometric_Line; --------------------------- -- Text Representation -- --------------------------- function mysql_text (collection : Geometry; top_first : Boolean := True) return String; function Well_Known_Text (collection : Geometry; top_first : Boolean := True) return String; function dump (collection : Geometry) return String; CONVERSION_FAILED : exception; OUT_OF_COLLECTION_RANGE : exception; LACKING_POINTS : exception; ILLEGAL_POLY_HOLE : exception; ILLEGAL_SHAPE : exception; private subtype Geometric_Point_Collection is Geometric_Point_set; subtype Item_ID_type is Positive range 1 .. 2 ** 10; -- 1024 shapes type collection_flags is mod 2 ** 24; type Ring_Structure is record Item_Type : Collection_Type; Item_ID : Item_ID_type; Ring_ID : Geo_Units; Ring_Size : Geo_Points; Ring_Count : Geo_Units; Point_Index : Geo_Points; Level_Flags : collection_flags; Group_ID : Item_ID_type; end record; type Ring_Structures is array (Positive range <>) of Ring_Structure; type Geometric_Polygon (rings : Geo_Units := Geo_Units'First; points : Geo_Points := Geo_Points'First) is record structures : Ring_Structures (1 .. rings); points_set : Geometric_Point_Collection (1 .. points) := (others => Origin_Point); end record; type Geometry (contents : Collection_Type := unset; units : Geo_Units := Geo_Units'First; subunits : Geo_Units := Geo_Units'First; points : Geo_Points := Geo_Points'First) is record case contents is when unset => null; when others => structures : Ring_Structures (1 .. subunits); points_set : Geometric_Point_Collection (1 .. points); end case; end record; -- returns a trimmed floating point image function format_real (value : Geometric_Real) return String; -- returns the highest value for Level Flags found function highest_level (collection : Geometry) return collection_flags; -- raises exception if index is out of range procedure check_collection_index (collection : Geometry; index : Positive); function single_canvas (gm_type : Collection_Type; items : Item_ID_type; subunits : Geo_Units; points : Geo_Points) return Geometry; end Spatial_Data;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt with CommonText; package Spatial_Data is package CT renames CommonText; type Collection_Type is (unset, single_point, single_line_string, single_polygon, multi_point, multi_line_string, multi_polygon, heterogeneous); type Geometric_Shape is (point_shape, line_string_shape, polygon_shape, mixture); -- The range limits are necessary to avoid storage error warnings subtype Geo_Points is Positive range 1 .. 2 ** 20; subtype Geo_Units is Natural range 0 .. 2 ** 12; -- Mutable variant records must be limited if tagged -- However, limited geometry cannot work. We must be able to change the -- contents discriminate, so it meants this record cannot be tagged. type Geometry (contents : Collection_Type := unset; units : Geo_Units := Geo_Units'First; subunits : Geo_Units := Geo_Units'First; points : Geo_Points := Geo_Points'First) is private; type Geometric_Real is digits 18; type Geometric_Point is record X : Geometric_Real; Y : Geometric_Real; end record; type Geometric_Circle is record center_point : Geometric_Point; radius : Geometric_Real; end record; type Slope_Intercept is record slope : Geometric_Real; y_intercept : Geometric_Real; vertical : Boolean; end record; type Standard_Form is record A : Geometric_Real; B : Geometric_Real; C : Geometric_Real; end record; type Geometric_Point_set is array (Positive range <>) of Geometric_Point; subtype Geometric_Ring is Geometric_Point_set; subtype Geometric_Line_String is Geometric_Point_set; subtype Geometric_Line is Geometric_Line_String (1 .. 2); type Geometric_Polygon (rings : Geo_Units := Geo_Units'First; points : Geo_Points := Geo_Points'First) is private; Origin_Point : constant Geometric_Point := (0.0, 0.0); -------------------------------- -- Initialization functions -- -------------------------------- function start_polygon (outer_ring : Geometric_Ring) return Geometric_Polygon; procedure append_inner_ring (polygon : in out Geometric_Polygon; inner_ring : Geometric_Ring); function initialize_as_point (point : Geometric_Point) return Geometry; function initialize_as_multi_point (point : Geometric_Point) return Geometry; function initialize_as_line (line_string : Geometric_Line_String) return Geometry; function initialize_as_multi_line (line_string : Geometric_Line_String) return Geometry; function initialize_as_polygon (polygon : Geometric_Polygon) return Geometry; function initialize_as_multi_polygon (polygon : Geometric_Polygon) return Geometry; function initialize_as_collection (anything : Geometry) return Geometry; ----------------------------------- -- Build collections functions -- ----------------------------------- procedure augment_multi_point (collection : in out Geometry; point : Geometric_Point); procedure augment_multi_line (collection : in out Geometry; line : Geometric_Line_String); procedure augment_multi_polygon (collection : in out Geometry; polygon : Geometric_Polygon); procedure augment_collection (collection : in out Geometry; anything : Geometry); --------------------------- -- Retrieval functions -- --------------------------- function type_of_collection (collection : Geometry) return Collection_Type; function size_of_collection (collection : Geometry) return Positive; function collection_item_type (collection : Geometry; index : Positive := 1) return Collection_Type; function retrieve_subcollection (collection : Geometry; index : Positive := 1) return Geometry; function retrieve_point (collection : Geometry; index : Positive := 1) return Geometric_Point; function retrieve_line (collection : Geometry; index : Positive := 1) return Geometric_Line_String; function retrieve_polygon (collection : Geometry; index : Positive := 1) return Geometric_Polygon; function number_of_rings (polygon : Geometric_Polygon) return Natural; function retrieve_ring (polygon : Geometric_Polygon; ring_index : Positive) return Geometric_Ring; ------------------- -- Conversions -- ------------------- function convert_infinite_line (line : Geometric_Line) return Slope_Intercept; function convert_infinite_line (line : Geometric_Line) return Standard_Form; function convert_to_infinite_line (std_form : Standard_Form) return Geometric_Line; function convert_to_infinite_line (intercept_form : Slope_Intercept) return Geometric_Line; --------------------------- -- Text Representation -- --------------------------- function mysql_text (collection : Geometry; top_first : Boolean := True) return String; function Well_Known_Text (collection : Geometry; top_first : Boolean := True) return String; function dump (collection : Geometry) return String; CONVERSION_FAILED : exception; OUT_OF_COLLECTION_RANGE : exception; LACKING_POINTS : exception; ILLEGAL_POLY_HOLE : exception; ILLEGAL_SHAPE : exception; private subtype Geometric_Point_Collection is Geometric_Point_set; subtype Item_ID_type is Positive range 1 .. 2 ** 10; -- 1024 shapes type collection_flags is mod 2 ** 24; type Ring_Structure is record Item_Type : Collection_Type; Item_ID : Item_ID_type; Ring_ID : Geo_Units; Ring_Size : Geo_Points; Ring_Count : Geo_Units; Point_Index : Geo_Points; Level_Flags : collection_flags; Group_ID : Item_ID_type; end record; type Ring_Structures is array (Positive range <>) of Ring_Structure; type Geometric_Polygon (rings : Geo_Units := Geo_Units'First; points : Geo_Points := Geo_Points'First) is record structures : Ring_Structures (1 .. rings); points_set : Geometric_Point_Collection (1 .. points) := (others => Origin_Point); end record; type Geometry (contents : Collection_Type := unset; units : Geo_Units := Geo_Units'First; subunits : Geo_Units := Geo_Units'First; points : Geo_Points := Geo_Points'First) is record case contents is when unset => null; when others => structures : Ring_Structures (1 .. subunits); points_set : Geometric_Point_Collection (1 .. points); end case; end record; -- returns a trimmed floating point image function format_real (value : Geometric_Real) return String; -- returns the highest value for Level Flags found function highest_level (collection : Geometry) return collection_flags; -- raises exception if index is out of range procedure check_collection_index (collection : Geometry; index : Positive); function single_canvas (gm_type : Collection_Type; items : Item_ID_type; subunits : Geo_Units; points : Geo_Points) return Geometry; function collection_item_shape (collection : Geometry; index : Positive := 1) return Geometric_Shape; end Spatial_Data;
Make collection_item_shape private
Make collection_item_shape private This is only used for exception message and isn't really very helpful. Rather than remove it completely, just remove it from public view.
Ada
isc
jrmarino/AdaBase
4c9984551adabca2e50dbb9446d8169437aa5d36
src/mysql/ado-statements-mysql.ads
src/mysql/ado-statements-mysql.ads
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- 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 System; with Mysql.Mysql; use Mysql.Mysql; with ADO.SQL; with ADO.Schemas; package ADO.Statements.Mysql is -- ------------------------------ -- Delete statement -- ------------------------------ type Mysql_Delete_Statement is new Delete_Statement with private; type Mysql_Delete_Statement_Access is access all Mysql_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : in Mysql_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Mysql_Update_Statement is new Update_Statement with private; type Mysql_Update_Statement_Access is access all Mysql_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Update_Statement; Result : out Integer); -- Create an update statement function Create_Statement (Database : in Mysql_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Mysql_Insert_Statement is new Insert_Statement with private; type Mysql_Insert_Statement_Access is access all Mysql_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : in Mysql_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for MySQL -- ------------------------------ type Mysql_Query_Statement is new Query_Statement with private; type Mysql_Query_Statement_Access is access all Mysql_Query_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Mysql_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Mysql_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Mysql_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Mysql_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Mysql_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Mysql_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Mysql_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Mysql_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Mysql_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Mysql_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; overriding procedure Finalize (Query : in out Mysql_Query_Statement); -- Create the query statement. function Create_Statement (Database : in Mysql_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; function Create_Statement (Database : in Mysql_Access; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Fields is array (Natural) of System.Address; type Row_Fields is access Fields; type Lengths is array (Natural) of Natural; type Lengths_Access is access Lengths; type Mysql_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : Mysql_Access; Result : MYSQL_RES; Row : System_Access; Counter : Natural := 1; Status : State := DONE; Lengths : Lengths_Access; Max_Column : Natural; end record; -- Get a column field address. -- If the query was not executed, raises Invalid_Statement -- If the column is out of bound, raises Constraint_Error function Get_Field (Query : Mysql_Query_Statement'Class; Column : Natural) return chars_ptr; -- Get a column field length. -- If the query was not executed, raises Invalid_Statement -- If the column is out of bound, raises Constraint_Error -- ------------------------------ function Get_Field_Length (Query : in Mysql_Query_Statement'Class; Column : in Natural) return Natural; type Mysql_Delete_Statement is new Delete_Statement with record Connection : Mysql_Access; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Mysql_Update_Statement is new Update_Statement with record Connection : Mysql_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Mysql_Insert_Statement is new Insert_Statement with record Connection : Mysql_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Mysql;
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- 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 System; with Mysql.Mysql; use Mysql.Mysql; with ADO.SQL; with ADO.Schemas; package ADO.Statements.Mysql is -- ------------------------------ -- Delete statement -- ------------------------------ type Mysql_Delete_Statement is new Delete_Statement with private; type Mysql_Delete_Statement_Access is access all Mysql_Delete_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Delete_Statement; Result : out Natural); -- Create the delete statement function Create_Statement (Database : in Mysql_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access; -- ------------------------------ -- Update statement -- ------------------------------ type Mysql_Update_Statement is new Update_Statement with private; type Mysql_Update_Statement_Access is access all Mysql_Update_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Update_Statement); -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Update_Statement; Result : out Integer); -- Create an update statement function Create_Statement (Database : in Mysql_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access; -- ------------------------------ -- Insert statement -- ------------------------------ type Mysql_Insert_Statement is new Insert_Statement with private; type Mysql_Insert_Statement_Access is access all Mysql_Insert_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Insert_Statement; Result : out Integer); -- Create an insert statement. function Create_Statement (Database : in Mysql_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access; -- ------------------------------ -- Query statement for MySQL -- ------------------------------ type Mysql_Query_Statement is new Query_Statement with private; type Mysql_Query_Statement_Access is access all Mysql_Query_Statement'Class; -- Execute the query overriding procedure Execute (Stmt : in out Mysql_Query_Statement); -- Get the number of rows returned by the query overriding function Get_Row_Count (Query : in Mysql_Query_Statement) return Natural; -- Returns True if there is more data (row) to fetch overriding function Has_Elements (Query : in Mysql_Query_Statement) return Boolean; -- Fetch the next row overriding procedure Next (Query : in out Mysql_Query_Statement); -- Returns true if the column <b>Column</b> is null. overriding function Is_Null (Query : in Mysql_Query_Statement; Column : in Natural) return Boolean; -- Get the column value at position <b>Column</b> and -- return it as an <b>Int64</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Int64 (Query : Mysql_Query_Statement; Column : Natural) return Int64; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Unbounded_String (Query : Mysql_Query_Statement; Column : Natural) return Unbounded_String; -- Get the column value at position <b>Column</b> and -- return it as an <b>Unbounded_String</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_String (Query : Mysql_Query_Statement; Column : Natural) return String; -- Get the column value at position <b>Column</b> and -- return it as a <b>Blob</b> reference. overriding function Get_Blob (Query : in Mysql_Query_Statement; Column : in Natural) return ADO.Blob_Ref; -- Get the column value at position <b>Column</b> and -- return it as an <b>Time</b>. -- Raises <b>Invalid_Type</b> if the value cannot be converted. -- Raises <b>Invalid_Column</b> if the column does not exist. function Get_Time (Query : Mysql_Query_Statement; Column : Natural) return Ada.Calendar.Time; -- Get the column type -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Type (Query : Mysql_Query_Statement; Column : Natural) return ADO.Schemas.Column_Type; -- Get the column name. -- Raises <b>Invalid_Column</b> if the column does not exist. overriding function Get_Column_Name (Query : in Mysql_Query_Statement; Column : in Natural) return String; -- Get the number of columns in the result. overriding function Get_Column_Count (Query : in Mysql_Query_Statement) return Natural; overriding procedure Finalize (Query : in out Mysql_Query_Statement); -- Create the query statement. function Create_Statement (Database : in Mysql_Access; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access; function Create_Statement (Database : in Mysql_Access; Query : in String) return Query_Statement_Access; private type State is (HAS_ROW, HAS_MORE, DONE, ERROR); type Fields is array (Natural) of System.Address; type Row_Fields is access Fields; type Lengths is array (Natural) of Natural; type Lengths_Access is access Lengths; type Mysql_Query_Statement is new Query_Statement with record This_Query : aliased ADO.SQL.Query; Connection : Mysql_Access; Result : MYSQL_RES; Row : System_Access; Counter : Natural := 1; Status : State := DONE; Lengths : Lengths_Access; Max_Column : Natural; end record; -- Get a column field address. -- If the query was not executed, raises Invalid_Statement -- If the column is out of bound, raises Constraint_Error function Get_Field (Query : Mysql_Query_Statement'Class; Column : Natural) return chars_ptr; -- Get a column field length. -- If the query was not executed, raises Invalid_Statement -- If the column is out of bound, raises Constraint_Error -- ------------------------------ function Get_Field_Length (Query : in Mysql_Query_Statement'Class; Column : in Natural) return Natural; type Mysql_Delete_Statement is new Delete_Statement with record Connection : Mysql_Access; Table : ADO.Schemas.Class_Mapping_Access; Delete_Query : aliased ADO.SQL.Query; end record; type Mysql_Update_Statement is new Update_Statement with record Connection : Mysql_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; type Mysql_Insert_Statement is new Insert_Statement with record Connection : Mysql_Access; This_Query : aliased ADO.SQL.Update_Query; Table : ADO.Schemas.Class_Mapping_Access; end record; end ADO.Statements.Mysql;
Define the Get_Column_Name and Get_Column_Count operation in the MySQL driver
Define the Get_Column_Name and Get_Column_Count operation in the MySQL driver
Ada
apache-2.0
Letractively/ada-ado
78436c982289aba8f9039a83681041c965984283
ARM/STMicro/STM32/boards/stm32f469_discovery/stm32-board.ads
ARM/STMicro/STM32/boards/stm32f469_discovery/stm32-board.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F469 Discovery kits -- manufactured by ST Microelectronics. with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; -- with STM32.SPI; use STM32.SPI; with STM32.ADC; use STM32.ADC; with STM32.FMC; use STM32.FMC; with Ada.Interrupts.Names; use Ada.Interrupts; use STM32; -- for base addresses package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; LED1 : User_Led renames PG6; LED2 : User_LED renames PD4; LED3 : User_LED renames PD5; LED4 : User_LED renames PK3; Green : User_LED renames LED1; Orange : User_LED renames LED2; Red : User_LED renames LED3; Blue : User_LED renames LED4; LCH_LED : User_LED renames Red; All_LEDs : constant GPIO_Points := LED1 & LED2 & LED3 & LED4; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : User_LED) renames STM32.GPIO.Clear; procedure Turn_Off (This : User_LED) renames STM32.GPIO.Set; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LEDs (These : GPIO_Points) renames STM32.GPIO.Toggle; -- Gyro : Three_Axis_Gyroscope; -- GPIO Pins for FMC FMC_D : constant GPIO_Points := (PD14, PD15, PD0, PD1, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15, PD8, PD9, PD10, PH8, PH9, PH10, PH11, PH12, PH13, PH14, PH15, PI0, PI1, PI2, PI3, PI6, PI7, PI9, PI10); FMC_A : constant GPIO_Points := (PF0, PF1, PF2, PF3, PF4, PF5, PF12, PF13, PF14, PF15, PG0, PG1, PG4, PG5); FMC_SDNWE : GPIO_Point renames PC0; FMC_SDNRAS : GPIO_Point renames PF11; FMC_SDNCAS : GPIO_Point renames PG15; FMC_SDNE0 : GPIO_Point renames PH3; FMC_SDCKE0 : GPIO_Point renames PH2; FMC_SDCLK : GPIO_Point renames PG8; FMC_NBL0 : GPIO_Point renames PE0; FMC_NBL1 : GPIO_Point renames PE1; FMC_NBL2 : GPIO_Point renames PI4; FMC_NBL3 : GPIO_Point renames PI5; SDRAM_PINS : constant GPIO_Points := FMC_A & FMC_D & FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK & FMC_SDNE0 & FMC_SDCKE0 & FMC_NBL0 & FMC_NBL1 & FMC_NBL2 & FMC_NBL3; -- SDRAM CONFIGURATION Parameters SDRAM_Base : constant := 16#C0000000#; SDRAM_Size : constant := 16#800000#; SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank := STM32.FMC.FMC_Bank1_SDRAM; SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width := STM32.FMC.FMC_SDMemory_Width_32b; SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits := FMC_RowBits_Number_12b; SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency := STM32.FMC.FMC_CAS_Latency_3; SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration := STM32.FMC.FMC_SDClock_Period_2; SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read := STM32.FMC.FMC_Read_Burst_Single; SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay := STM32.FMC.FMC_ReadPipe_Delay_0; SDRAM_Refresh_Cnt : constant := 1385; --------------- -- SPI5 Pins -- --------------- -- SPI5_SCK : GPIO_Point renames PF7; -- SPI5_MISO : GPIO_Point renames PF8; -- SPI5_MOSI : GPIO_Point renames PF9; -- NCS_MEMS_SPI : GPIO_Point renames PC1; -- MEMS_INT1 : GPIO_Point renames PA1; -- MEMS_INT2 : GPIO_Point renames PA2; -- LCD_SPI : SPI_Port renames SPI_5; ------------------------ -- GPIO Pins for LCD -- ------------------------ LCD_XRES : GPIO_Point renames PH7; LCD_BL_CTRL : GPIO_Point renames PA3; DSIHOST_TE : GPIO_Point renames PJ2; -- User button User_Button_Point : GPIO_Point renames PA0; User_Button_Interrupt : constant Interrupt_Id := Names.EXTI0_Interrupt; procedure Configure_User_Button_GPIO; -- Configures the GPIO port/pin for the blue user button. Sufficient -- for polling the button, and necessary for having the button generate -- interrupts. end STM32.Board;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- This file provides declarations for devices on the STM32F469 Discovery kits -- manufactured by ST Microelectronics. with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; -- with STM32.SPI; use STM32.SPI; with STM32.ADC; use STM32.ADC; with STM32.FMC; use STM32.FMC; with Ada.Interrupts.Names; use Ada.Interrupts; use STM32; -- for base addresses package STM32.Board is pragma Elaborate_Body; subtype User_LED is GPIO_Point; LED1 : User_Led renames PG6; LED2 : User_LED renames PD4; LED3 : User_LED renames PD5; LED4 : User_LED renames PK3; Green : User_LED renames LED1; Orange : User_LED renames LED2; Red : User_LED renames LED3; Blue : User_LED renames LED4; LCH_LED : User_LED renames Red; All_LEDs : constant GPIO_Points := LED1 & LED2 & LED3 & LED4; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Turn_On (This : User_LED) renames STM32.GPIO.Clear; procedure Turn_Off (This : User_LED) renames STM32.GPIO.Set; procedure All_LEDs_Off with Inline; procedure All_LEDs_On with Inline; procedure Toggle_LEDs (These : GPIO_Points) renames STM32.GPIO.Toggle; -- Gyro : Three_Axis_Gyroscope; -- GPIO Pins for FMC FMC_D : constant GPIO_Points := (PD14, PD15, PD0, PD1, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15, PD8, PD9, PD10, PH8, PH9, PH10, PH11, PH12, PH13, PH14, PH15, PI0, PI1, PI2, PI3, PI6, PI7, PI9, PI10); FMC_A : constant GPIO_Points := (PF0, PF1, PF2, PF3, PF4, PF5, PF12, PF13, PF14, PF15, PG0, PG1, PG4, PG5); FMC_SDNWE : GPIO_Point renames PC0; FMC_SDNRAS : GPIO_Point renames PF11; FMC_SDNCAS : GPIO_Point renames PG15; FMC_SDNE0 : GPIO_Point renames PH3; FMC_SDCKE0 : GPIO_Point renames PH2; FMC_SDCLK : GPIO_Point renames PG8; FMC_NBL0 : GPIO_Point renames PE0; FMC_NBL1 : GPIO_Point renames PE1; FMC_NBL2 : GPIO_Point renames PI4; FMC_NBL3 : GPIO_Point renames PI5; SDRAM_PINS : constant GPIO_Points := FMC_A & FMC_D & FMC_SDNWE & FMC_SDNRAS & FMC_SDNCAS & FMC_SDCLK & FMC_SDNE0 & FMC_SDCKE0 & FMC_NBL0 & FMC_NBL1 & FMC_NBL2 & FMC_NBL3; -- SDRAM CONFIGURATION Parameters SDRAM_Base : constant := 16#C0000000#; SDRAM_Size : constant := 16#800000#; SDRAM_Bank : constant STM32.FMC.FMC_SDRAM_Cmd_Target_Bank := STM32.FMC.FMC_Bank1_SDRAM; SDRAM_Mem_Width : constant STM32.FMC.FMC_SDRAM_Memory_Bus_Width := STM32.FMC.FMC_SDMemory_Width_32b; SDRAM_Row_Bits : constant STM32.FMC.FMC_SDRAM_Row_Address_Bits := FMC_RowBits_Number_11b; SDRAM_CAS_Latency : constant STM32.FMC.FMC_SDRAM_CAS_Latency := STM32.FMC.FMC_CAS_Latency_3; SDRAM_CLOCK_Period : constant STM32.FMC.FMC_SDRAM_Clock_Configuration := STM32.FMC.FMC_SDClock_Period_2; SDRAM_Read_Burst : constant STM32.FMC.FMC_SDRAM_Burst_Read := STM32.FMC.FMC_Read_Burst_Single; SDRAM_Read_Pipe : constant STM32.FMC.FMC_SDRAM_Read_Pipe_Delay := STM32.FMC.FMC_ReadPipe_Delay_0; SDRAM_Refresh_Cnt : constant := 1385; --------------- -- SPI5 Pins -- --------------- -- SPI5_SCK : GPIO_Point renames PF7; -- SPI5_MISO : GPIO_Point renames PF8; -- SPI5_MOSI : GPIO_Point renames PF9; -- NCS_MEMS_SPI : GPIO_Point renames PC1; -- MEMS_INT1 : GPIO_Point renames PA1; -- MEMS_INT2 : GPIO_Point renames PA2; -- LCD_SPI : SPI_Port renames SPI_5; ------------------------ -- GPIO Pins for LCD -- ------------------------ LCD_XRES : GPIO_Point renames PH7; LCD_BL_CTRL : GPIO_Point renames PA3; DSIHOST_TE : GPIO_Point renames PJ2; -- User button User_Button_Point : GPIO_Point renames PA0; User_Button_Interrupt : constant Interrupt_Id := Names.EXTI0_Interrupt; procedure Configure_User_Button_GPIO; -- Configures the GPIO port/pin for the blue user button. Sufficient -- for polling the button, and necessary for having the button generate -- interrupts. end STM32.Board;
Fix SDRAM parameters for the STM32F469-Disco board.
Fix SDRAM parameters for the STM32F469-Disco board.
Ada
bsd-3-clause
AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
19ae42aa4f53b09ed0bb6b0fc9bb84de68f95441
src/sys/encoders/util-encoders-aes.ads
src/sys/encoders/util-encoders-aes.ads
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; private with Ada.Finalization; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type AES_Padding is (NO_PADDING, PKCS7_PADDING); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); AES_128_Length : constant := 16; AES_192_Length : constant := 24; AES_256_Length : constant := 32; subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16); subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24); subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32); type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32; procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Secret_Key) with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32; procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Secret_Key) with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32; procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Decrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); type Cipher is tagged limited private; -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (E : in out Cipher; IV : in Word_Block_Type); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Cipher and Util.Encoders.Transformer with private; -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Secret_Key; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) with Pre => Into'Length >= Block_Type'Length, Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length - 1; -- Encrypt the secret using the encoder and return the encrypted value in the buffer. procedure Encrypt_Secret (E : in out Encoder; Secret : in Secret_Key; Into : out Ada.Streams.Stream_Element_Array); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Decoder is new Cipher and Util.Encoders.Transformer with private; -- Set the decryption key to use. procedure Set_Key (E : in out Decoder; Data : in Secret_Key; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset); -- Finish encoding the input array. overriding procedure Finish (E : in out Decoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset); -- Decrypt the content using the decoder and build the secret key. procedure Decrypt_Secret (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Secret : out Secret_Key); private use Interfaces; subtype Count_Type is Ada.Streams.Stream_Element_Offset range 0 .. 16; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key := (others => 0); Rounds : Natural := 0; end record; type Cipher is limited new Ada.Finalization.Limited_Controlled with record IV : Word_Block_Type := (others => 0); Key : Key_Type; Mode : AES_Mode := CBC; Padding : AES_Padding := PKCS7_PADDING; Data_Count : Count_Type := 0; Data : Block_Type; Data2 : Block_Type; end record; overriding procedure Finalize (Object : in out Cipher); type Encoder is new Cipher and Util.Encoders.Transformer with null record; type Decoder is new Cipher and Util.Encoders.Transformer with null record; end Util.Encoders.AES;
----------------------------------------------------------------------- -- util-encoders-aes -- AES encryption and decryption -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; private with Ada.Finalization; -- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to -- RFC3174 or [FIPS-180-1]. package Util.Encoders.AES is type AES_Mode is (ECB, CBC, PCBC, CFB, OFB, CTR); type AES_Padding is (NO_PADDING, ZERO_PADDING, PKCS7_PADDING); type Key_Type is private; -- ------------------------------ -- ------------------------------ subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16); AES_128_Length : constant := 16; AES_192_Length : constant := 24; AES_256_Length : constant := 32; subtype AES_128_Key is Ada.Streams.Stream_Element_Array (1 .. 16); subtype AES_192_Key is Ada.Streams.Stream_Element_Array (1 .. 24); subtype AES_256_Key is Ada.Streams.Stream_Element_Array (1 .. 32); type Word_Block_Type is array (1 .. 4) of Interfaces.Unsigned_32; procedure Set_Encrypt_Key (Key : out Key_Type; Data : in Secret_Key) with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32; procedure Set_Decrypt_Key (Key : out Key_Type; Data : in Secret_Key) with Pre => Data.Length = 16 or Data.Length = 24 or Data.Length = 32; procedure Encrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array; Output : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Key : in Key_Type); procedure Decrypt (Input : in Block_Type; Output : out Block_Type; Key : in Key_Type); procedure Decrypt (Input : in Word_Block_Type; Output : out Word_Block_Type; Key : in Key_Type); type Cipher is tagged limited private; -- Set the encryption initialization vector before starting the encryption. procedure Set_IV (E : in out Cipher; IV : in Word_Block_Type); -- Set the padding. procedure Set_Padding (E : in out Cipher; Padding : in AES_Padding); -- Get the padding used. function Padding (E : in Cipher) return AES_Padding; -- Return true if the cipher has a encryption/decryption key configured. function Has_Key (E : in Cipher) return Boolean; -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Encoder is new Cipher and Util.Encoders.Transformer with private; -- Set the encryption key to use. procedure Set_Key (E : in out Encoder; Data : in Secret_Key; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Encoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) with Pre => E.Has_Key; -- Finish encoding the input array. overriding procedure Finish (E : in out Encoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) with Pre => E.Has_Key and Into'Length >= Block_Type'Length, Post => Last = Into'First - 1 or Last = Into'First + Block_Type'Length - 1; -- Encrypt the secret using the encoder and return the encrypted value in the buffer. -- The target buffer must be a multiple of 16-bytes block. procedure Encrypt_Secret (E : in out Encoder; Secret : in Secret_Key; Into : out Ada.Streams.Stream_Element_Array) with Pre => Into'Length mod 16 = 0 and (case E.Padding is when NO_PADDING => Secret.Length = Into'Length, when PKCS7_PADDING | ZERO_PADDING => 16 * (1 + (Secret.Length / 16)) = Into'Length); -- ------------------------------ -- AES encoder -- ------------------------------ -- This <b>Encoder</b> translates the (binary) input stream into -- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF. type Decoder is new Cipher and Util.Encoders.Transformer with private; -- Set the decryption key to use. procedure Set_Key (E : in out Decoder; Data : in Secret_Key; Mode : in AES_Mode := CBC); -- Encodes the binary input stream represented by <b>Data</b> into -- an SHA-1 hash output stream <b>Into</b>. -- -- If the transformer does not have enough room to write the result, -- it must return in <b>Encoded</b> the index of the last encoded -- position in the <b>Data</b> stream. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output stream <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- stream cannot be transformed. overriding procedure Transform (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) with Pre => E.Has_Key; -- Finish encoding the input array. overriding procedure Finish (E : in out Decoder; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset); -- Decrypt the content using the decoder and build the secret key. procedure Decrypt_Secret (E : in out Decoder; Data : in Ada.Streams.Stream_Element_Array; Secret : in out Secret_Key) with Pre => Data'Length mod 16 = 0 and (case E.Padding is when NO_PADDING => Secret.Length = Data'Length, when PKCS7_PADDING | ZERO_PADDING => 16 * (1 + (Secret.Length / 16)) = Data'Length); private use Interfaces; subtype Count_Type is Ada.Streams.Stream_Element_Offset range 0 .. 16; type Block_Key is array (0 .. 59) of Unsigned_32; type Key_Type is record Key : Block_Key := (others => 0); Rounds : Natural := 0; end record; type Cipher is limited new Ada.Finalization.Limited_Controlled with record IV : Word_Block_Type := (others => 0); Key : Key_Type; Mode : AES_Mode := CBC; Padding : AES_Padding := PKCS7_PADDING; Data_Count : Count_Type := 0; Data : Block_Type; Data2 : Block_Type; end record; overriding procedure Finalize (Object : in out Cipher); type Encoder is new Cipher and Util.Encoders.Transformer with null record; type Decoder is new Cipher and Util.Encoders.Transformer with null record; end Util.Encoders.AES;
Add Set_Padding, Has_Padding and Has_Key operations Add preconditions on Encrypt_Secret, Decrypt_Secret and Transform
Add Set_Padding, Has_Padding and Has_Key operations Add preconditions on Encrypt_Secret, Decrypt_Secret and Transform
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4bc4c59160840ee82c98e5bd964381fd4cbaa0b5
src/util-log-loggers.ads
src/util-log-loggers.ads
----------------------------------------------------------------------- -- Logs -- Utility Log Package -- Copyright (C) 2006, 2008, 2009, 2011 Free Software Foundation, Inc. -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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.Strings.Unbounded; with Util.Log.Appenders; with Util.Properties; with Ada.Finalization; package Util.Log.Loggers is use Ada.Exceptions; use Ada.Strings.Unbounded; -- The logger identifies and configures the log produced -- by a component that uses it. The logger has a name -- which can be printed in the log outputs. The logger instance -- contains a log level which can be used to control the level of -- logs. type Logger is tagged limited private; type Logger_Access is access constant Logger; -- Create a logger with the given name. function Create (Name : in String) return Logger; -- Create a logger with the given name and use the specified level. function Create (Name : in String; Level : in Level_Type) return Logger; -- Initialize the logger and create a logger with the given name. function Create (Name : in String; Config : in String) return Logger; -- Change the log level procedure Set_Level (Log : in out Logger; Level : in Level_Type); -- Get the log level. function Get_Level (Log : in Logger) return Level_Type; -- Get the log level name. function Get_Level_Name (Log : in Logger) return String; procedure Print (Log : in Logger; Level : in Level_Type; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""; Arg4 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in String := ""; Arg3 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in Unbounded_String; Arg3 : in String := ""); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in String := ""; Arg3 : in String := ""); procedure Warn (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Error (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Error (Log : in Logger'Class; Message : in String; E : in Exception_Occurrence; Trace : in Boolean := False); -- Set the appender that will handle the log events procedure Set_Appender (Log : in out Logger'Class; Appender : in Util.Log.Appenders.Appender_Access); -- Initialize the log environment with the property file. procedure Initialize (Name : in String); -- Initialize the log environment with the properties. procedure Initialize (Properties : in Util.Properties.Manager); type Logger_Info (<>) is limited private; -- Get the logger name. function Get_Logger_Name (Log : in Logger_Info) return String; -- Return a printable traceback that correspond to the exception. function Traceback (E : in Exception_Occurrence) return String; private type Logger_Info_Access is access all Logger_Info; type Logger_Info (Len : Positive) is record Next_Logger : Logger_Info_Access; Prev_Logger : Logger_Info_Access; Level : Level_Type := INFO_LEVEL; Appender : Util.Log.Appenders.Appender_Access; Name : String (1 .. Len); end record; type Logger is new Ada.Finalization.Limited_Controlled with record Instance : Logger_Info_Access; end record; -- Finalize the logger and flush the associated appender overriding procedure Finalize (Log : in out Logger); end Util.Log.Loggers;
----------------------------------------------------------------------- -- util-log-loggers -- Utility Log Package -- Copyright (C) 2006, 2008, 2009, 2011, 2018 Free Software Foundation, Inc. -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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.Strings.Unbounded; with Util.Log.Appenders; with Util.Properties; with Ada.Finalization; package Util.Log.Loggers is use Ada.Exceptions; use Ada.Strings.Unbounded; -- The logger identifies and configures the log produced -- by a component that uses it. The logger has a name -- which can be printed in the log outputs. The logger instance -- contains a log level which can be used to control the level of -- logs. type Logger is tagged limited private; type Logger_Access is access constant Logger; -- Create a logger with the given name. function Create (Name : in String) return Logger; -- Create a logger with the given name and use the specified level. function Create (Name : in String; Level : in Level_Type) return Logger; -- Initialize the logger and create a logger with the given name. function Create (Name : in String; Config : in String) return Logger; -- Change the log level procedure Set_Level (Log : in out Logger; Level : in Level_Type); -- Get the log level. function Get_Level (Log : in Logger) return Level_Type; -- Get the log level name. function Get_Level_Name (Log : in Logger) return String; procedure Print (Log : in Logger; Level : in Level_Type; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""; Arg4 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in String := ""; Arg3 : in String := ""); procedure Debug (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in Unbounded_String; Arg3 : in String := ""); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Info (Log : in Logger'Class; Message : in String; Arg1 : in Unbounded_String; Arg2 : in String := ""; Arg3 : in String := ""); procedure Warn (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Error (Log : in Logger'Class; Message : in String; Arg1 : in String := ""; Arg2 : in String := ""; Arg3 : in String := ""); procedure Error (Log : in Logger'Class; Message : in String; E : in Exception_Occurrence; Trace : in Boolean := False); -- Set the appender that will handle the log events procedure Set_Appender (Log : in out Logger'Class; Appender : in Util.Log.Appenders.Appender_Access); -- Initialize the log environment with the property file. procedure Initialize (Name : in String); -- Initialize the log environment with the properties. procedure Initialize (Properties : in Util.Properties.Manager); type Logger_Info (<>) is limited private; -- Get the logger name. function Get_Logger_Name (Log : in Logger_Info) return String; -- Return a printable traceback that correspond to the exception. function Traceback (E : in Exception_Occurrence) return String; private type Logger_Info_Access is access all Logger_Info; type Logger_Info (Len : Positive) is record Next_Logger : Logger_Info_Access; Prev_Logger : Logger_Info_Access; Level : Level_Type := INFO_LEVEL; Appender : Util.Log.Appenders.Appender_Access; Name : String (1 .. Len); end record; type Logger is new Ada.Finalization.Limited_Controlled with record Instance : Logger_Info_Access; end record; -- Finalize the logger and flush the associated appender overriding procedure Finalize (Log : in out Logger); end Util.Log.Loggers;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
44c5965be1f8921296eb699c98b7cb55b0c80707
src/wiki-render-text.adb
src/wiki-render-text.adb
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; end Render_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href"); begin Engine.Open_Paragraph; if Title'Length /= 0 then Engine.Output.Write (Title); end if; if Title /= Href and Href'Length /= 0 then if Title'Length /= 0 then Engine.Output.Write (" ("); end if; Engine.Output.Write (Href); if Title'Length /= 0 then Engine.Output.Write (")"); end if; end if; Engine.Empty_Line := False; end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc"); begin Engine.Open_Paragraph; if Title'Length > 0 then Engine.Output.Write (Title); end if; if Title'Length > 0 and Desc'Length > 0 then Engine.Output.Write (' '); end if; if Desc'Length > 0 then Engine.Output.Write (Desc); end if; Engine.Empty_Line := False; end Render_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Render_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is pragma Unreferenced (Doc); begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the no-newline mode to produce a single line text (disabled by default). -- ------------------------------ procedure Set_No_Newline (Engine : in out Text_Renderer; Enable : in Boolean) is begin Engine.No_Newline := Enable; end Set_No_Newline; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; end Render_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href"); begin Engine.Open_Paragraph; if Title'Length /= 0 then Engine.Output.Write (Title); end if; if Title /= Href and Href'Length /= 0 then if Title'Length /= 0 then Engine.Output.Write (" ("); end if; Engine.Output.Write (Href); if Title'Length /= 0 then Engine.Output.Write (")"); end if; end if; Engine.Empty_Line := False; end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc"); begin Engine.Open_Paragraph; if Title'Length > 0 then Engine.Output.Write (Title); end if; if Title'Length > 0 and Desc'Length > 0 then Engine.Output.Write (' '); end if; if Desc'Length > 0 then Engine.Output.Write (Desc); end if; Engine.Empty_Line := False; end Render_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_NEWLINE => if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); else Engine.Output.Write (' '); end if; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Render_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is pragma Unreferenced (Doc); begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
Add Set_No_Newline and ignore the newlines when this mode is enabled
Add Set_No_Newline and ignore the newlines when this mode is enabled
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ea843c635a256b48a929048bccf73a6db4f3caaa
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Strings; with ADO; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Helpers.Beans; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; with AWA.Workspaces.Beans; package body AWA.Workspaces.Tests is use Ada.Strings.Unbounded; use AWA.Tests; function Get_Invitation_Bean is new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean, Element_Access => Beans.Invitation_Bean_Access); package Caller is new Util.Test_Caller (Test, "Workspaces.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send", Test_Invite_User'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Key : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "This invitation is invalid"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key, "invitation-bad2.html"); ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid"); if Key = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html"); ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test sending an invitation. -- ------------------------------ procedure Test_Invite_User (T : in out Test) is use type ADO.Identifier; use type AWA.Workspaces.Beans.Invitation_Bean_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Invite : AWA.Workspaces.Beans.Invitation_Bean_Access; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("message", "I invite you to this application"); Request.Set_Parameter ("send", "1"); Request.Set_Parameter ("invite", "1"); ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after invitation creation"); -- Verify the invitation by looking at the inviteUser bean. Invite := Get_Invitation_Bean (Request, "inviteUser"); T.Assert (Invite /= null, "Null inviteUser bean"); T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid"); T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null"); end Test_Invite_User; end AWA.Workspaces.Tests;
----------------------------------------------------------------------- -- awa-workspaces-tests -- Unit tests for workspaces and invitations -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Strings; with ADO; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Principals; with ASF.Helpers.Beans; with ASF.Tests; with AWA.Users.Models; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with Security.Contexts; with AWA.Workspaces.Beans; package body AWA.Workspaces.Tests is use Ada.Strings.Unbounded; use AWA.Tests; function Get_Invitation_Bean is new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean, Element_Access => Beans.Invitation_Bean_Access); package Caller is new Util.Test_Caller (Test, "Workspaces.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send", Test_Invite_User'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Key : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "This invitation is invalid"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key, "invitation-bad2.html"); ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid"); if Key = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html"); ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid"); end Verify_Anonymous; -- ------------------------------ -- Test sending an invitation. -- ------------------------------ procedure Test_Invite_User (T : in out Test) is use type ADO.Identifier; use type AWA.Workspaces.Beans.Invitation_Bean_Access; Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Invite : AWA.Workspaces.Beans.Invitation_Bean_Access; Check : AWA.Workspaces.Beans.Invitation_Bean; Key : AWA.Users.Models.Access_Key_Ref; Outcome : Ada.Strings.Unbounded.Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("message", "I invite you to this application"); Request.Set_Parameter ("send", "1"); Request.Set_Parameter ("invite", "1"); ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_OK, "Invalid response after invitation creation"); -- Verify the invitation by looking at the inviteUser bean. Invite := Get_Invitation_Bean (Request, "inviteUser"); T.Assert (Invite /= null, "Null inviteUser bean"); T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid"); T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null"); Check.Key := Invite.Get_Access_Key.Get_Access_Key; Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("success"); Check.Load (Outcome); Util.Tests.Assert_Equals (T, "success", To_String (Outcome), "Invalid invitation key"); end Test_Invite_User; end AWA.Workspaces.Tests;
Update the invitation test to load the invitation after it is created
Update the invitation test to load the invitation after it is created
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
5778c72cf69603a1eb424979afe623ad91a1e5f9
src/asf-applications-main.adb
src/asf-applications-main.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Streams; with ASF.Contexts.Writer; with ASF.Components.Core; with ASF.Components.Core.Factory; with ASF.Components.Html.Factory; with ASF.Components.Utils.Factory; with ASF.Views.Nodes.Core; with ASF.Views.Nodes.Facelets; with EL.Expressions; with EL.Contexts.Default; with Ada.Exceptions; with Ada.Containers.Vectors; package body ASF.Applications.Main is use Util.Log; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main"); -- ------------------------------ -- Get the application view handler. -- ------------------------------ function Get_View_Handler (App : access Application) return access Views.View_Handler'Class is begin return App.View'Unchecked_Access; end Get_View_Handler; -- ------------------------------ -- Initialize the application -- ------------------------------ procedure Initialize (App : in out Application; Conf : in Config) is use ASF.Components; use ASF.Views; begin App.Conf := Conf; App.Set_Init_Parameters (Params => Conf); ASF.Factory.Register (Factory => App.Components, Bindings => Core.Factory.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Html.Factory.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Nodes.Core.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Nodes.Facelets.Definition); ASF.Components.Utils.Factory.Set_Functions (App.Functions); ASF.Views.Nodes.Core.Set_Functions (App.Functions); App.View.Initialize (App.Components'Unchecked_Access, Conf); ASF.Modules.Initialize (App.Modules, Conf); ASF.Locales.Initialize (App.Locales, App.Factory, Conf); end Initialize; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get_Config (App : Application; Param : Config_Param) return String is begin return App.Conf.Get (Param); end Get_Config; -- ------------------------------ -- Set a global variable in the global EL contexts. -- ------------------------------ procedure Set_Global (App : in out Application; Name : in String; Value : in String) is begin App.Set_Global (Name, EL.Objects.To_Object (Value)); end Set_Global; procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object) is begin App.Globals.Bind (Name, Value); end Set_Global; -- ------------------------------ -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. -- ------------------------------ function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Value : constant EL.Expressions.Value_Expression := App.Globals.Get_Variable (Name); begin return Value.Get_Value (Context); end Get_Global; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (App : in out Application; Name : in String; Handler : in Create_Bean_Access; Free : in Free_Bean_Access := null; Scope : in Scope_Type := REQUEST_SCOPE) is begin ASF.Beans.Register (App.Factory, Name, Handler, Free, Scope); end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out EL.Beans.Readonly_Bean_Access; Free : out Free_Bean_Access; Scope : out Scope_Type) is begin ASF.Beans.Create (App.Factory, Name, Result, Free, Scope); end Create; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in ASF.Modules.Module_Access; Name : in String; URI : in String := "") is begin ASF.Modules.Register (App.Modules'Unchecked_Access, Module, Name, URI); Module.Register_Factory (App.Factory); App.View.Register_Module (Module); end Register; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Register (App : in out Application; Name : in String; Bundle : in String) is begin ASF.Locales.Register (App.Locales, App.Factory, Name, Bundle); end Register; -- ------------------------------ -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. -- ------------------------------ procedure Add_Converter (App : in out Application; Name : in String; Converter : access ASF.Converters.Converter'Class) is begin ASF.Factory.Register (Factory => App.Components, Name => Name, Converter => Converter.all'Unchecked_Access); end Add_Converter; -- ------------------------------ -- Closes the application -- ------------------------------ procedure Close (App : in out Application) is begin ASF.Applications.Views.Close (App.View); end Close; type Bean_Object is record Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; end record; package Bean_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Bean_Object); type Bean_Vector_Access is access all Bean_Vectors.Vector; -- ------------------------------ -- Default Resolver -- ------------------------------ type Web_ELResolver is new EL.Contexts.ELResolver with record Request : EL.Contexts.Default.Default_ELResolver_Access; Application : Main.Application_Access; Beans : Bean_Vector_Access; end record; overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object; overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is use EL.Objects; use EL.Beans; use EL.Variables; Result : Object := Resolver.Request.Get_Value (Context, Base, Name); Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access := null; Scope : Scope_Type; begin if not EL.Objects.Is_Null (Result) then return Result; end if; Resolver.Application.Create (Name, Bean, Free, Scope); if Bean = null then return Resolver.Application.Get_Global (Name, Context); -- raise No_Variable -- with "Bean not found: '" & To_String (Name) & "'"; end if; Resolver.Beans.Append (Bean_Object '(Bean, Free)); Result := To_Object (Bean); Resolver.Request.Register (Name, Result); return Result; end Get_Value; -- Set the value associated with a base object and a given property. overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Resolver.Request.Set_Value (Context, Base, Name, Value); end Set_Value; -- ------------------------------ -- Set the current faces context before processing a view. -- ------------------------------ procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access) is begin Context.Get_ELContext.Set_Function_Mapper (App.Functions'Unchecked_Access); ASF.Contexts.Faces.Set_Current (Context, App'Unchecked_Access); end Set_Context; -- ------------------------------ -- Dispatch the request received on a page. -- ------------------------------ procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; use ASF.Applications.Views; use Ada.Exceptions; Writer : aliased ASF.Contexts.Writer.ResponseWriter; Context : aliased ASF.Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Req_Resolver : aliased Default_ELResolver; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Log.Info ("Dispatch {0}", Page); Root_Resolver.Application := App'Unchecked_Access; Root_Resolver.Request := Req_Resolver'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Writer.Initialize ("text/html", "UTF-8", Output); Context.Set_Request (Request'Unchecked_Access); Context.Set_Response (Response'Unchecked_Access); App.Set_Context (Context'Unchecked_Access); begin Handler.Restore_View (Page, Context, View); exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin Handler.Render_View (Context, View); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null and then Bean.Free /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; end Dispatch; -- ------------------------------ -- Dispatch the request received on a page. -- ------------------------------ procedure Postback (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; use ASF.Applications.Views; use Ada.Exceptions; Writer : aliased ASF.Contexts.Writer.ResponseWriter; Context : aliased ASF.Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Req_Resolver : aliased Default_ELResolver; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Log.Info ("Dispatch {0}", Page); Root_Resolver.Application := App'Unchecked_Access; Root_Resolver.Request := Req_Resolver'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Writer.Initialize ("text/html", "UTF-8", Output); Context.Set_Request (Request'Unchecked_Access); Context.Set_Response (Response'Unchecked_Access); App.Set_Context (Context'Unchecked_Access); begin Handler.Restore_View (Page, Context, View); exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin View.Get_Root.Process_Decodes (Context); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin View.Get_Root.Process_Updates (Context); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin Handler.Render_View (Context, View); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null and then Bean.Free /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; end Postback; -- ------------------------------ -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. -- ------------------------------ function Find (App : in Application; Name : in EL.Objects.Object) return access ASF.Converters.Converter'Class is begin return ASF.Factory.Find (App.Components, Name); end Find; -- ------------------------------ -- Register some functions -- ------------------------------ procedure Register_Functions (App : in out Application'Class) is begin Set_Functions (App.Functions); end Register_Functions; end ASF.Applications.Main;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Streams; with ASF.Contexts.Writer; with ASF.Components.Core; with ASF.Components.Core.Factory; with ASF.Components.Html.Factory; with ASF.Components.Utils.Factory; with ASF.Views.Nodes.Core; with ASF.Views.Nodes.Facelets; with EL.Expressions; with EL.Contexts.Default; with Ada.Exceptions; with Ada.Containers.Vectors; package body ASF.Applications.Main is use Util.Log; use Ada.Strings.Unbounded; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Applications.Main"); -- ------------------------------ -- Get the application view handler. -- ------------------------------ function Get_View_Handler (App : access Application) return access Views.View_Handler'Class is begin return App.View'Unchecked_Access; end Get_View_Handler; -- ------------------------------ -- Initialize the application -- ------------------------------ procedure Initialize (App : in out Application; Conf : in Config) is use ASF.Components; use ASF.Views; begin App.Conf := Conf; App.Set_Init_Parameters (Params => Conf); ASF.Factory.Register (Factory => App.Components, Bindings => Core.Factory.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Html.Factory.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Nodes.Core.Definition); ASF.Factory.Register (Factory => App.Components, Bindings => Nodes.Facelets.Definition); ASF.Components.Utils.Factory.Set_Functions (App.Functions); ASF.Views.Nodes.Core.Set_Functions (App.Functions); App.View.Initialize (App.Components'Unchecked_Access, Conf); ASF.Modules.Initialize (App.Modules, Conf); ASF.Locales.Initialize (App.Locales, App.Factory, Conf); end Initialize; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get_Config (App : Application; Param : Config_Param) return String is begin return App.Conf.Get (Param); end Get_Config; -- ------------------------------ -- Set a global variable in the global EL contexts. -- ------------------------------ procedure Set_Global (App : in out Application; Name : in String; Value : in String) is begin App.Set_Global (Name, EL.Objects.To_Object (Value)); end Set_Global; procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object) is begin App.Globals.Bind (Name, Value); end Set_Global; -- ------------------------------ -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. -- ------------------------------ function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Value : constant EL.Expressions.Value_Expression := App.Globals.Get_Variable (Name); begin return Value.Get_Value (Context); end Get_Global; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (App : in out Application; Name : in String; Handler : in Create_Bean_Access; Free : in Free_Bean_Access := null; Scope : in Scope_Type := REQUEST_SCOPE) is begin ASF.Beans.Register (App.Factory, Name, Handler, Free, Scope); end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out EL.Beans.Readonly_Bean_Access; Free : out Free_Bean_Access; Scope : out Scope_Type) is begin ASF.Beans.Create (App.Factory, Name, Result, Free, Scope); end Create; -- ------------------------------ -- Register the module in the application -- ------------------------------ procedure Register (App : in out Application; Module : in ASF.Modules.Module_Access; Name : in String; URI : in String := "") is begin ASF.Modules.Register (App.Modules'Unchecked_Access, Module, Name, URI); Module.Register_Factory (App.Factory); App.View.Register_Module (Module); end Register; -- ------------------------------ -- Register a bundle and bind it to a facelet variable. -- ------------------------------ procedure Register (App : in out Application; Name : in String; Bundle : in String) is begin ASF.Locales.Register (App.Locales, App.Factory, Name, Bundle); end Register; -- ------------------------------ -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. -- ------------------------------ procedure Add_Converter (App : in out Application; Name : in String; Converter : access ASF.Converters.Converter'Class) is begin ASF.Factory.Register (Factory => App.Components, Name => Name, Converter => Converter.all'Unchecked_Access); end Add_Converter; -- ------------------------------ -- Closes the application -- ------------------------------ procedure Close (App : in out Application) is begin ASF.Applications.Views.Close (App.View); end Close; type Bean_Object is record Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access; end record; package Bean_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Bean_Object); type Bean_Vector_Access is access all Bean_Vectors.Vector; -- ------------------------------ -- Default Resolver -- ------------------------------ type Web_ELResolver is new EL.Contexts.ELResolver with record Request : ASF.Requests.Request_Access; Application : Main.Application_Access; Beans : Bean_Vector_Access; end record; overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object; overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object); -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : Web_ELResolver; Context : EL.Contexts.ELContext'Class; Base : access EL.Beans.Readonly_Bean'Class; Name : Unbounded_String) return EL.Objects.Object is use EL.Objects; use EL.Beans; use EL.Variables; Result : Object; Bean : EL.Beans.Readonly_Bean_Access; Free : ASF.Beans.Free_Bean_Access := null; Scope : Scope_Type; Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; Result := Resolver.Request.Get_Attribute (Key); if not EL.Objects.Is_Null (Result) then return Result; end if; Resolver.Application.Create (Name, Bean, Free, Scope); if Bean = null then return Resolver.Application.Get_Global (Name, Context); -- raise No_Variable -- with "Bean not found: '" & To_String (Name) & "'"; end if; Resolver.Beans.Append (Bean_Object '(Bean, Free)); Result := To_Object (Bean); Resolver.Request.Set_Attribute (Key, Result); return Result; end Get_Value; -- Set the value associated with a base object and a given property. overriding procedure Set_Value (Resolver : in Web_ELResolver; Context : in EL.Contexts.ELContext'Class; Base : access EL.Beans.Bean'Class; Name : in Unbounded_String; Value : in EL.Objects.Object) is pragma Unreferenced (Context); Key : constant String := To_String (Name); begin if Base /= null then Base.Set_Value (Name => Key, Value => Value); else Resolver.Request.Set_Attribute (Name => Key, Value => Value); end if; end Set_Value; -- ------------------------------ -- Set the current faces context before processing a view. -- ------------------------------ procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access) is begin Context.Get_ELContext.Set_Function_Mapper (App.Functions'Unchecked_Access); ASF.Contexts.Faces.Set_Current (Context, App'Unchecked_Access); end Set_Context; -- ------------------------------ -- Dispatch the request received on a page. -- ------------------------------ procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; use ASF.Applications.Views; use Ada.Exceptions; Writer : aliased ASF.Contexts.Writer.ResponseWriter; Context : aliased ASF.Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Log.Info ("Dispatch {0}", Page); Root_Resolver.Application := App'Unchecked_Access; Root_Resolver.Request := Request'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Writer.Initialize ("text/html", "UTF-8", Output); Context.Set_Request (Request'Unchecked_Access); Context.Set_Response (Response'Unchecked_Access); App.Set_Context (Context'Unchecked_Access); begin Handler.Restore_View (Page, Context, View); exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin Handler.Render_View (Context, View); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null and then Bean.Free /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; end Dispatch; -- ------------------------------ -- Dispatch the request received on a page. -- ------------------------------ procedure Postback (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; use EL.Beans; use ASF.Applications.Views; use Ada.Exceptions; Writer : aliased ASF.Contexts.Writer.ResponseWriter; Context : aliased ASF.Contexts.Faces.Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Root_Resolver : aliased Web_ELResolver; Beans : aliased Bean_Vectors.Vector; -- Get the view handler Handler : constant access View_Handler'Class := App.Get_View_Handler; Output : constant ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Log.Info ("Dispatch {0}", Page); Root_Resolver.Application := App'Unchecked_Access; Root_Resolver.Request := Request'Unchecked_Access; Root_Resolver.Beans := Beans'Unchecked_Access; ELContext.Set_Resolver (Root_Resolver'Unchecked_Access); ELContext.Set_Variable_Mapper (Variables'Unchecked_Access); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Response_Writer (Writer'Unchecked_Access); Writer.Initialize ("text/html", "UTF-8", Output); Context.Set_Request (Request'Unchecked_Access); Context.Set_Response (Response'Unchecked_Access); App.Set_Context (Context'Unchecked_Access); begin Handler.Restore_View (Page, Context, View); exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin View.Get_Root.Process_Decodes (Context); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin View.Get_Root.Process_Updates (Context); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; begin Handler.Render_View (Context, View); exception when E: others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end; Writer.Flush; declare C : Bean_Vectors.Cursor := Beans.First; begin while Bean_Vectors.Has_Element (C) loop declare Bean : Bean_Object := Bean_Vectors.Element (C); begin if Bean.Bean /= null and then Bean.Free /= null then Bean.Free (Bean.Bean); end if; end; Bean_Vectors.Next (C); end loop; end; end Postback; -- ------------------------------ -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. -- ------------------------------ function Find (App : in Application; Name : in EL.Objects.Object) return access ASF.Converters.Converter'Class is begin return ASF.Factory.Find (App.Components, Name); end Find; -- ------------------------------ -- Register some functions -- ------------------------------ procedure Register_Functions (App : in out Application'Class) is begin Set_Functions (App.Functions); end Register_Functions; end ASF.Applications.Main;
Store the beans created for the request on the request object by using Set_Attribute and Get_Attribute to retrieve them.
Store the beans created for the request on the request object by using Set_Attribute and Get_Attribute to retrieve them.
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
0c057d927ab9dc83040ebc3cf1dd541a15d08b93
src/asf-applications-main.ads
src/asf-applications-main.ads
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Basic; with Util.Locales; with EL.Objects; with EL.Contexts; with EL.Functions; with EL.Functions.Default; with EL.Expressions; with EL.Variables.Default; with Ada.Strings.Unbounded; with ASF.Locales; with ASF.Factory; with ASF.Converters; with ASF.Validators; with ASF.Contexts.Faces; with ASF.Contexts.Exceptions; with ASF.Lifecycles; with ASF.Applications.Views; with ASF.Navigations; with ASF.Beans; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Events.Faces.Actions; with Security.Policies; use Security; with Security.OAuth.Servers; package ASF.Applications.Main is use ASF.Beans; -- ------------------------------ -- Factory for creation of lifecycle, view handler -- ------------------------------ type Application_Factory is tagged limited private; -- Create the lifecycle handler. The lifecycle handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object. -- It can be overriden to change the behavior of the ASF request lifecycle. function Create_Lifecycle_Handler (App : in Application_Factory) return ASF.Lifecycles.Lifecycle_Access; -- Create the view handler. The view handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Applications.Views.View_Handler</b> object. -- It can be overriden to change the views associated with the application. function Create_View_Handler (App : in Application_Factory) return ASF.Applications.Views.View_Handler_Access; -- Create the navigation handler. The navigation handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Navigations.Navigation_Handler</b> object. -- It can be overriden to change the navigations associated with the application. function Create_Navigation_Handler (App : in Application_Factory) return ASF.Navigations.Navigation_Handler_Access; -- Create the security policy manager. The security policy manager is created during -- the initialization phase of the application. The default implementation -- creates a <b>Security.Policies.Policy_Manager</b> object. function Create_Security_Manager (App : in Application_Factory) return Security.Policies.Policy_Manager_Access; -- Create the OAuth application manager. The OAuth application manager is created -- during the initialization phase of the application. The default implementation -- creates a <b>Security.OAuth.Servers.Auth_Manager</b> object. function Create_OAuth_Manager (App : in Application_Factory) return Security.OAuth.Servers.Auth_Manager_Access; -- Create the exception handler. The exception handler is created during -- the initialization phase of the application. The default implementation -- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object. function Create_Exception_Handler (App : in Application_Factory) return ASF.Contexts.Exceptions.Exception_Handler_Access; -- ------------------------------ -- Application -- ------------------------------ type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with private; type Application_Access is access all Application'Class; -- Get the application view handler. function Get_View_Handler (App : access Application) return access Views.View_Handler'Class; -- Get the lifecycle handler. function Get_Lifecycle_Handler (App : in Application) return ASF.Lifecycles.Lifecycle_Access; -- Get the navigation handler. function Get_Navigation_Handler (App : in Application) return ASF.Navigations.Navigation_Handler_Access; -- Get the permission manager associated with this application. function Get_Security_Manager (App : in Application) return Security.Policies.Policy_Manager_Access; -- Get the OAuth application manager associated with this application. function Get_OAuth_Manager (App : in Application) return Security.OAuth.Servers.Auth_Manager_Access; -- Get the action event listener responsible for processing action -- events and triggering the navigation to the next view using the -- navigation handler. function Get_Action_Listener (App : in Application) return ASF.Events.Faces.Actions.Action_Listener_Access; -- Process the action associated with the action event. The action returns -- and outcome which is then passed to the navigation handler to navigate to -- the next view. overriding procedure Process_Action (Listener : in Application; Event : in ASF.Events.Faces.Actions.Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class); -- Execute the action method. The action returns and outcome which is then passed -- to the navigation handler to navigate to the next view. procedure Process_Action (Listener : in Application; Method : in EL.Expressions.Method_Info; Context : in out Contexts.Faces.Faces_Context'Class); -- Initialize the application procedure Initialize (App : in out Application; Conf : in Config; Factory : in out Application_Factory'Class); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. procedure Initialize_Components (App : in out Application); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. procedure Initialize_Config (App : in out Application; Conf : in out Config); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. procedure Initialize_Filters (App : in out Application); -- Finalizes the application, freeing the memory. overriding procedure Finalize (App : in out Application); -- Get the configuration parameter; function Get_Config (App : Application; Param : Config_Param) return String; -- Set a global variable in the global EL contexts. procedure Set_Global (App : in out Application; Name : in String; Value : in String); procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object); -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Get the list of supported locales for this application. function Get_Supported_Locales (App : in Application) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (App : in Application) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Handler : in Application; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Register a bundle and bind it to a facelet variable. procedure Register (App : in out Application; Name : in String; Bundle : in String); -- 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 (App : in out Application; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (App : in out Application; Name : in String; Class : in ASF.Beans.Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (App : in out Application; Name : in String; Handler : in ASF.Beans.Create_Bean_Access); -- Create a bean by using the create operation registered for the name procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type); -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. procedure Add_Converter (App : in out Application; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Register a binding library in the factory. procedure Add_Components (App : in out Application; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Closes the application procedure Close (App : in out Application); -- Set the current faces context before processing a view. procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access); -- Execute the lifecycle phases on the faces context. procedure Execute_Lifecycle (App : in Application; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Dispatch the request received on a page. procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Dispatch a bean action request. -- 1. Find the bean object identified by <b>Name</b>, create it if necessary. -- 2. Resolve the bean method identified by <b>Operation</b>. -- 3. If the method is an action method (see ASF.Events.Actions), call that method. -- 4. Using the outcome action result, decide using the navigation handler what -- is the result view. -- 5. Render the result view resolved by the navigation handler. procedure Dispatch (App : in out Application; Name : in String; Operation : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class)); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (App : in Application; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find_Validator (App : in Application; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Register some functions generic with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); procedure Register_Functions (App : in out Application'Class); -- Register some bean definitions. generic with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); procedure Register_Beans (App : in out Application'Class); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (App : in out Application; Name : in String; Locale : in String; Bundle : out ASF.Locales.Bundle); private type Application_Factory is tagged limited null record; type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with record View : aliased ASF.Applications.Views.View_Handler; Lifecycle : ASF.Lifecycles.Lifecycle_Access; Factory : aliased ASF.Beans.Bean_Factory; Locales : ASF.Locales.Factory; Globals : aliased EL.Variables.Default.Default_Variable_Mapper; Functions : aliased EL.Functions.Default.Default_Function_Mapper; -- The component factory Components : aliased ASF.Factory.Component_Factory; -- The action listener. Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access; -- The navigation handler. Navigation : ASF.Navigations.Navigation_Handler_Access; -- The permission manager. Permissions : Security.Policies.Policy_Manager_Access; -- The OAuth application manager. OAuth : Security.OAuth.Servers.Auth_Manager_Access; end record; end ASF.Applications.Main;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- 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 Util.Beans.Basic; with Util.Locales; with EL.Objects; with EL.Contexts; with EL.Functions; with EL.Functions.Default; with EL.Expressions; with EL.Variables.Default; with Ada.Strings.Unbounded; with ASF.Locales; with ASF.Factory; with ASF.Converters; with ASF.Validators; with ASF.Contexts.Faces; with ASF.Contexts.Exceptions; with ASF.Lifecycles; with ASF.Applications.Views; with ASF.Navigations; with ASF.Beans; with ASF.Requests; with ASF.Responses; with ASF.Servlets; with ASF.Events.Faces.Actions; with Security.Policies; use Security; with Security.OAuth.Servers; package ASF.Applications.Main is use ASF.Beans; -- ------------------------------ -- Factory for creation of lifecycle, view handler -- ------------------------------ type Application_Factory is tagged limited private; -- Create the lifecycle handler. The lifecycle handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Lifecycles.Default.Default_Lifecycle</b> object. -- It can be overriden to change the behavior of the ASF request lifecycle. function Create_Lifecycle_Handler (App : in Application_Factory) return ASF.Lifecycles.Lifecycle_Access; -- Create the view handler. The view handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Applications.Views.View_Handler</b> object. -- It can be overriden to change the views associated with the application. function Create_View_Handler (App : in Application_Factory) return ASF.Applications.Views.View_Handler_Access; -- Create the navigation handler. The navigation handler is created during -- the initialization phase of the application. The default implementation -- creates an <b>ASF.Navigations.Navigation_Handler</b> object. -- It can be overriden to change the navigations associated with the application. function Create_Navigation_Handler (App : in Application_Factory) return ASF.Navigations.Navigation_Handler_Access; -- Create the security policy manager. The security policy manager is created during -- the initialization phase of the application. The default implementation -- creates a <b>Security.Policies.Policy_Manager</b> object. function Create_Security_Manager (App : in Application_Factory) return Security.Policies.Policy_Manager_Access; -- Create the OAuth application manager. The OAuth application manager is created -- during the initialization phase of the application. The default implementation -- creates a <b>Security.OAuth.Servers.Auth_Manager</b> object. function Create_OAuth_Manager (App : in Application_Factory) return Security.OAuth.Servers.Auth_Manager_Access; -- Create the exception handler. The exception handler is created during -- the initialization phase of the application. The default implementation -- creates a <b>ASF.Contexts.Exceptions.Exception_Handler</b> object. function Create_Exception_Handler (App : in Application_Factory) return ASF.Contexts.Exceptions.Exception_Handler_Access; -- ------------------------------ -- Application -- ------------------------------ type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with private; type Application_Access is access all Application'Class; -- Get the application view handler. function Get_View_Handler (App : access Application) return access Views.View_Handler'Class; -- Get the lifecycle handler. function Get_Lifecycle_Handler (App : in Application) return ASF.Lifecycles.Lifecycle_Access; -- Get the navigation handler. function Get_Navigation_Handler (App : in Application) return ASF.Navigations.Navigation_Handler_Access; -- Get the permission manager associated with this application. function Get_Security_Manager (App : in Application) return Security.Policies.Policy_Manager_Access; -- Get the OAuth application manager associated with this application. function Get_OAuth_Manager (App : in Application) return Security.OAuth.Servers.Auth_Manager_Access; -- Get the action event listener responsible for processing action -- events and triggering the navigation to the next view using the -- navigation handler. function Get_Action_Listener (App : in Application) return ASF.Events.Faces.Actions.Action_Listener_Access; -- Process the action associated with the action event. The action returns -- and outcome which is then passed to the navigation handler to navigate to -- the next view. overriding procedure Process_Action (Listener : in Application; Event : in ASF.Events.Faces.Actions.Action_Event'Class; Context : in out Contexts.Faces.Faces_Context'Class); -- Execute the action method. The action returns and outcome which is then passed -- to the navigation handler to navigate to the next view. procedure Process_Action (Listener : in Application; Method : in EL.Expressions.Method_Info; Context : in out Contexts.Faces.Faces_Context'Class); -- Initialize the application procedure Initialize (App : in out Application; Conf : in Config; Factory : in out Application_Factory'Class); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. procedure Initialize_Components (App : in out Application); -- Initialize the application configuration properties. Properties defined in <b>Conf</b> -- are expanded by using the EL expression resolver. procedure Initialize_Config (App : in out Application; Conf : in out Config); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. procedure Initialize_Filters (App : in out Application); -- Finalizes the application, freeing the memory. overriding procedure Finalize (App : in out Application); -- Get the configuration parameter; function Get_Config (App : Application; Param : Config_Param) return String; -- Set a global variable in the global EL contexts. procedure Set_Global (App : in out Application; Name : in String; Value : in String); procedure Set_Global (App : in out Application; Name : in String; Value : in EL.Objects.Object); -- Resolve a global variable and return its value. -- Raises the <b>EL.Functions.No_Variable</b> exception if the variable does not exist. function Get_Global (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Get the list of supported locales for this application. function Get_Supported_Locales (App : in Application) return Util.Locales.Locale_Array; -- Add the locale to the list of supported locales. procedure Add_Supported_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Get the default locale defined by the application. function Get_Default_Locale (App : in Application) return Util.Locales.Locale; -- Set the default locale defined by the application. procedure Set_Default_Locale (App : in out Application; Locale : in Util.Locales.Locale); -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. function Calculate_Locale (Handler : in Application; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale; -- Register a bundle and bind it to a facelet variable. procedure Register (App : in out Application; Name : in String; Bundle : in String); -- 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 (App : in out Application; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (App : in out Application; Name : in String; Class : in ASF.Beans.Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (App : in out Application; Name : in String; Handler : in ASF.Beans.Create_Bean_Access); -- Create a bean by using the create operation registered for the name procedure Create (App : in Application; Name : in Ada.Strings.Unbounded.Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type); -- Add a converter in the application. The converter is referenced by -- the specified name in the XHTML files. procedure Add_Converter (App : in out Application; Name : in String; Converter : in ASF.Converters.Converter_Access); -- Register a binding library in the factory. procedure Add_Components (App : in out Application; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Closes the application procedure Close (App : in out Application); -- Set the current faces context before processing a view. procedure Set_Context (App : in out Application; Context : in ASF.Contexts.Faces.Faces_Context_Access); -- Execute the lifecycle phases on the faces context. procedure Execute_Lifecycle (App : in Application; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Dispatch the request received on a page. procedure Dispatch (App : in out Application; Page : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); -- Dispatch a bean action request. -- 1. Find the bean object identified by <b>Name</b>, create it if necessary. -- 2. Resolve the bean method identified by <b>Operation</b>. -- 3. If the method is an action method (see ASF.Events.Actions), call that method. -- 4. Using the outcome action result, decide using the navigation handler what -- is the result view. -- 5. Render the result view resolved by the navigation handler. procedure Dispatch (App : in out Application; Name : in String; Operation : in String; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Prepare : access procedure (Bean : access Util.Beans.Basic.Bean'Class)); -- Find the converter instance that was registered under the given name. -- Returns null if no such converter exist. function Find (App : in Application; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access; -- Find the validator instance that was registered under the given name. -- Returns null if no such validator exist. function Find_Validator (App : in Application; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access; -- Register some functions generic with procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class); procedure Register_Functions (App : in out Application'Class); -- Register some bean definitions. generic with procedure Set_Beans (Factory : in out ASF.Beans.Bean_Factory); procedure Register_Beans (App : in out Application'Class); -- Load the resource bundle identified by the <b>Name</b> and for the given -- <b>Locale</b>. procedure Load_Bundle (App : in out Application; Name : in String; Locale : in String; Bundle : out ASF.Locales.Bundle); private type Application_Factory is tagged limited null record; type Application is new ASF.Servlets.Servlet_Registry and ASF.Events.Faces.Actions.Action_Listener with record View : aliased ASF.Applications.Views.View_Handler; Lifecycle : ASF.Lifecycles.Lifecycle_Access; Factory : aliased ASF.Beans.Bean_Factory; Locales : ASF.Locales.Factory; Globals : aliased EL.Variables.Default.Default_Variable_Mapper; Functions : aliased EL.Functions.Default.Default_Function_Mapper; -- The component factory Components : aliased ASF.Factory.Component_Factory; -- The action listener. Action_Listener : ASF.Events.Faces.Actions.Action_Listener_Access; -- The navigation handler. Navigation : ASF.Navigations.Navigation_Handler_Access; -- The permission manager. Permissions : Security.Policies.Policy_Manager_Access; -- The OAuth application manager. OAuth : Security.OAuth.Servers.Auth_Manager_Access; -- Exception handler Exceptions : ASF.Contexts.Exceptions.Exception_Handler_Access; end record; end ASF.Applications.Main;
Add the exception handler instance to the application
Add the exception handler instance to the application
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d5383384d687b5e110c7c39d76f1f84c38895464
src/asf-sessions-factory.adb
src/asf-sessions-factory.adb
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base64; with Util.Log.Loggers; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package body ASF.Sessions.Factory is use Ada.Finalization; use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory"); -- ------------------------------ -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. -- ------------------------------ procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access) is use Ada.Streams; use Interfaces; Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1); Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size); Encoder : Util.Encoders.Base64.Encoder; Last : Stream_Element_Offset; Encoded : Stream_Element_Offset; begin Factory.Lock.Write; -- Generate the random sequence. for I in 0 .. Factory.Id_Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Factory.Random); begin Rand (4 * I) := Stream_Element (Value and 16#0FF#); Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; Factory.Lock.Release_Write; -- Encode the random stream in base64 and save it into the Id string. Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); Id := new String (1 .. Natural (Encoded + 1)); for I in 0 .. Encoded loop Id (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; Log.Info ("Allocated session {0}", Id.all); end Allocate_Session_Id; -- ------------------------------ -- Create a new session -- ------------------------------ procedure Create_Session (Factory : in out Session_Factory; Result : out Session) is Sess : Session; Impl : constant Session_Record_Access := new Session_Record '(Ada.Finalization.Limited_Controlled with Ref_Counter => Util.Concurrent.Counters.ONE, Create_Time => Ada.Calendar.Clock, Max_Inactive => Factory.Max_Inactive, others => <>); begin Impl.Access_Time := Impl.Create_Time; Sess.Impl := Impl; Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id); Factory.Lock.Write; Factory.Sessions.Insert (Impl.Id.all'Access, Sess); Factory.Lock.Release_Write; Result := Sess; end Create_Session; -- ------------------------------ -- Deletes the session. -- ------------------------------ procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session) is begin null; end Delete_Session; -- ------------------------------ -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. -- ------------------------------ procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session) is begin Result := Null_Session; Factory.Lock.Read; declare Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access); begin if Session_Maps.Has_Element (Pos) then Result := Session_Maps.Element (Pos); end if; end; Factory.Lock.Release_Read; if Result.Is_Valid then Result.Impl.Access_Time := Ada.Calendar.Clock; Log.Info ("Found active session {0}", Id); else Log.Info ("Invalid session {0}", Id); end if; end Find_Session; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is begin return Factory.Max_Inactive; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration) is begin Factory.Max_Inactive := Interval; end Set_Max_Inactive_Interval; -- ------------------------------ -- Initialize the session factory. -- ------------------------------ overriding procedure Initialize (Factory : in out Session_Factory) is begin Id_Random.Reset (Factory.Random); end Initialize; end ASF.Sessions.Factory;
----------------------------------------------------------------------- -- asf.sessions.factory -- ASF Sessions factory -- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.Base64; with Util.Log.Loggers; -- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching -- and deleting sessions. package body ASF.Sessions.Factory is use Ada.Finalization; use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory"); -- ------------------------------ -- Allocate a unique and random session identifier. The default implementation -- generates a 256 bit random number that it serializes as base64 in the string. -- Upon successful completion, the sequence string buffer is allocated and -- returned in <b>Id</b>. The buffer will be freed when the session is removed. -- ------------------------------ procedure Allocate_Session_Id (Factory : in out Session_Factory; Id : out Ada.Strings.Unbounded.String_Access) is use Ada.Streams; Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1); Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size); Encoder : Util.Encoders.Base64.Encoder; Last : Stream_Element_Offset; Encoded : Stream_Element_Offset; begin Factory.Sessions.Generate_Id (Rand); -- Encode the random stream in base64 and save it into the Id string. Encoder.Transform (Data => Rand, Into => Buffer, Last => Last, Encoded => Encoded); Id := new String (1 .. Natural (Encoded + 1)); for I in 0 .. Encoded loop Id (Natural (I + 1)) := Character'Val (Buffer (I)); end loop; Log.Info ("Allocated session {0}", Id.all); end Allocate_Session_Id; -- ------------------------------ -- Create a new session -- ------------------------------ procedure Create_Session (Factory : in out Session_Factory; Result : out Session) is Sess : Session; Impl : constant Session_Record_Access := new Session_Record '(Ada.Finalization.Limited_Controlled with Ref_Counter => Util.Concurrent.Counters.ONE, Create_Time => Ada.Calendar.Clock, Max_Inactive => Factory.Max_Inactive, others => <>); begin Impl.Access_Time := Impl.Create_Time; Sess.Impl := Impl; Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id); Factory.Sessions.Insert (Sess); Result := Sess; end Create_Session; -- ------------------------------ -- Deletes the session. -- ------------------------------ procedure Delete_Session (Factory : in out Session_Factory; Sess : in out Session) is begin null; end Delete_Session; -- ------------------------------ -- Finds the session knowing the session identifier. -- If the session is found, the last access time is updated. -- Otherwise, the null session object is returned. -- ------------------------------ procedure Find_Session (Factory : in out Session_Factory; Id : in String; Result : out Session) is begin Result := Factory.Sessions.Find (Id); if Result.Is_Valid then Result.Impl.Access_Time := Ada.Calendar.Clock; Log.Info ("Found active session {0}", Id); else Log.Info ("Invalid session {0}", Id); end if; end Find_Session; -- ------------------------------ -- Returns the maximum time interval, in seconds, that the servlet container will -- keep this session open between client accesses. After this interval, the servlet -- container will invalidate the session. The maximum time interval can be set with -- the Set_Max_Inactive_Interval method. -- A negative time indicates the session should never timeout. -- ------------------------------ function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is begin return Factory.Max_Inactive; end Get_Max_Inactive_Interval; -- ------------------------------ -- Specifies the time, in seconds, between client requests before the servlet -- container will invalidate this session. A negative time indicates the session -- should never timeout. -- ------------------------------ procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory; Interval : in Duration) is begin Factory.Max_Inactive := Interval; end Set_Max_Inactive_Interval; -- ------------------------------ -- Initialize the session factory. -- ------------------------------ overriding procedure Initialize (Factory : in out Session_Factory) is begin Factory.Sessions.Initialize; end Initialize; protected body Session_Cache is -- ------------------------------ -- Find the session in the session cache. -- ------------------------------ function Find (Id : in String) return Session is Pos : constant Session_Maps.Cursor := Sessions.Find (Id'Unrestricted_Access); begin if Session_Maps.Has_Element (Pos) then return Session_Maps.Element (Pos); else return Null_Session; end if; end Find; -- ------------------------------ -- Insert the session in the session cache. -- ------------------------------ procedure Insert (Sess : in Session) is begin Sessions.Insert (Sess.Impl.Id.all'Access, Sess); end Insert; -- ------------------------------ -- Generate a random bitstream. -- ------------------------------ procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is use Ada.Streams; use Interfaces; Size : Stream_Element_Offset := Rand'Length / 4; begin -- Generate the random sequence. for I in 0 .. Size - 1 loop declare Value : constant Unsigned_32 := Id_Random.Random (Random); begin Rand (4 * I) := Stream_Element (Value and 16#0FF#); Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#); Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#); Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#); end; end loop; end Generate_Id; -- ------------------------------ -- Initialize the random generator. -- ------------------------------ procedure Initialize is begin Id_Random.Reset (Random); end Initialize; end Session_Cache; end ASF.Sessions.Factory;
Use a protected type for the session cache management and session id generation
Use a protected type for the session cache management and session id generation
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
bf888c73dc01094213a40ed61223d951ffb29217
awa/plugins/awa-jobs/src/awa-jobs-services.ads
awa/plugins/awa-jobs/src/awa-jobs-services.ads
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with ADO.Sessions; with AWA.Events; with AWA.Jobs.Models; package AWA.Jobs.Services is Closed_Error : exception; Schedule_Error : exception; Execute_Error : exception; Invalid_Value : exception; -- Event posted when a job is created. package Job_Create_Event is new AWA.Events.Definition (Name => "job-create"); -- Get the job status. function Get_Job_Status (Id : in ADO.Identifier) return AWA.Jobs.Models.Job_Status_Type; -- ------------------------------ -- Abstract_Job Type -- ------------------------------ -- The <b>Abstract_Job_Type</b> is an abstract tagged record which defines a job that can be -- scheduled and executed. type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Abstract_Job_Access is access all Abstract_Job_Type'Class; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. procedure Execute (Job : in out Abstract_Job_Type) is abstract; -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String; -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer; -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object; -- Get the job status. function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type; -- Get the job identifier once the job was scheduled. The job identifier allows to -- retrieve the job and check its execution and completion status later on. function Get_Identifier (Job : in Abstract_Job_Type) return ADO.Identifier; -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type); -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class); -- ------------------------------ -- Job Factory -- ------------------------------ -- The <b>Job_Factory</b> is the interface that allows to create a job instance in order -- to execute a scheduled job. type Job_Factory is abstract tagged limited null record; type Job_Factory_Access is access all Job_Factory'Class; -- Create the job instance using the job factory. function Create (Factory : in Job_Factory) return Abstract_Job_Access is abstract; -- Get the job factory name. function Get_Name (Factory : in Job_Factory'Class) return String; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class); -- ------------------------------ -- Work Factory -- ------------------------------ type Work_Access is access procedure (Job : in out Abstract_Job_Type'Class); type Work_Factory (Work : Work_Access) is new Job_Factory with null record; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access; -- ------------------------------ -- -- ------------------------------ type Job_Type is new Abstract_Job_Type with private; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class); procedure Execute (Job : in out Job_Type); -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. generic type T is new Abstract_Job_Type with private; package Definition is type Job_Type_Factory is new Job_Factory with null record; overriding function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access; Factory : aliased Job_Type_Factory; end Definition; generic Work : in Work_Access; package Work_Definition is type S_Factory is new Work_Factory with null record; Factory : aliased S_Factory := S_Factory '(Work => Work); end Work_Definition; -- Execute the job associated with the given event. procedure Execute (Event : in AWA.Events.Module_Event'Class); private -- Execute the job and save the job information in the database. procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class); type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with record Job : AWA.Jobs.Models.Job_Ref; Props : Util.Beans.Objects.Maps.Map; Results : Util.Beans.Objects.Maps.Map; Props_Modified : Boolean := False; Results_Modified : Boolean := False; end record; type Job_Type is new Abstract_Job_Type with record Work : Work_Access; end record; end AWA.Jobs.Services;
----------------------------------------------------------------------- -- awa-jobs -- AWA Jobs -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Maps; with ADO.Sessions; with AWA.Events; with AWA.Jobs.Models; package AWA.Jobs.Services is Closed_Error : exception; Schedule_Error : exception; Execute_Error : exception; Invalid_Value : exception; -- Event posted when a job is created. package Job_Create_Event is new AWA.Events.Definition (Name => "job-create"); -- Get the job status. function Get_Job_Status (Id : in ADO.Identifier) return AWA.Jobs.Models.Job_Status_Type; -- ------------------------------ -- Abstract_Job Type -- ------------------------------ -- The <b>Abstract_Job_Type</b> is an abstract tagged record which defines a job that can be -- scheduled and executed. type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Abstract_Job_Access is access all Abstract_Job_Type'Class; -- Execute the job. This operation must be implemented and should perform the work -- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve -- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result. procedure Execute (Job : in out Abstract_Job_Type) is abstract; -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in String); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Integer); -- Set the job parameter identified by the <b>Name</b> to the value given in <b>Value</b>. -- The value object can hold any kind of basic value type (integer, enum, date, strings). -- If the value represents a bean, the <tt>Invalid_Value</tt> exception is raised. procedure Set_Parameter (Job : in out Abstract_Job_Type; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the job parameter identified by the <b>Name</b> and convert the value into a string. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return String; -- Get the job parameter identified by the <b>Name</b> and convert the value as an integer. -- If the parameter is not defined, return the default value passed in <b>Default</b>. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String; Default : in Integer) return Integer; -- Get the job parameter identified by the <b>Name</b> and return it as a typed object. function Get_Parameter (Job : in Abstract_Job_Type; Name : in String) return Util.Beans.Objects.Object; -- Get the job status. function Get_Status (Job : in Abstract_Job_Type) return AWA.Jobs.Models.Job_Status_Type; -- Get the job identifier once the job was scheduled. The job identifier allows to -- retrieve the job and check its execution and completion status later on. function Get_Identifier (Job : in Abstract_Job_Type) return ADO.Identifier; -- Set the job status. -- When the job is terminated, it is closed and the job parameters or results cannot be -- changed. procedure Set_Status (Job : in out Abstract_Job_Type; Status : in AWA.Jobs.Models.Job_Status_Type); -- Save the job information in the database. Use the database session defined by <b>DB</b> -- to save the job. procedure Save (Job : in out Abstract_Job_Type; DB : in out ADO.Sessions.Master_Session'Class); -- ------------------------------ -- Job Factory -- ------------------------------ -- The <b>Job_Factory</b> is the interface that allows to create a job instance in order -- to execute a scheduled job. type Job_Factory is abstract tagged limited null record; type Job_Factory_Access is access all Job_Factory'Class; -- Create the job instance using the job factory. function Create (Factory : in Job_Factory) return Abstract_Job_Access is abstract; -- Get the job factory name. function Get_Name (Factory : in Job_Factory'Class) return String; -- Schedule the job. procedure Schedule (Job : in out Abstract_Job_Type; Definition : in Job_Factory'Class); -- ------------------------------ -- Work Factory -- ------------------------------ type Work_Access is access procedure (Job : in out Abstract_Job_Type'Class); type Work_Factory (Work : Work_Access) is new Job_Factory with null record; overriding function Create (Factory : in Work_Factory) return Abstract_Job_Access; -- ------------------------------ -- -- ------------------------------ type Job_Type is new Abstract_Job_Type with private; procedure Set_Work (Job : in out Job_Type; Work : in Work_Factory'Class); procedure Execute (Job : in out Job_Type); -- ------------------------------ -- Job Declaration -- ------------------------------ -- The <tt>Definition</tt> package must be instantiated with a given job type to -- register the new job definition. generic type T is new Abstract_Job_Type with private; package Definition is type Job_Type_Factory is new Job_Factory with null record; overriding function Create (Factory : in Job_Type_Factory) return Abstract_Job_Access; -- The job factory. Factory : constant Job_Factory_Access; private Instance : aliased Job_Type_Factory; Factory : constant Job_Factory_Access := Instance'Access; end Definition; generic Work : in Work_Access; package Work_Definition is type S_Factory is new Work_Factory with null record; -- The job factory. Factory : constant Job_Factory_Access; private Instance : aliased S_Factory := S_Factory '(Work => Work); Factory : constant Job_Factory_Access := Instance'Access; end Work_Definition; -- Execute the job associated with the given event. procedure Execute (Event : in AWA.Events.Module_Event'Class); private -- Execute the job and save the job information in the database. procedure Execute (Job : in out Abstract_Job_Type'Class; DB : in out ADO.Sessions.Master_Session'Class); type Abstract_Job_Type is abstract new Ada.Finalization.Limited_Controlled with record Job : AWA.Jobs.Models.Job_Ref; Props : Util.Beans.Objects.Maps.Map; Results : Util.Beans.Objects.Maps.Map; Props_Modified : Boolean := False; Results_Modified : Boolean := False; end record; type Job_Type is new Abstract_Job_Type with record Work : Work_Access; end record; end AWA.Jobs.Services;
Simplify the use of the job factory
Simplify the use of the job factory
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a2af31fea53125f5010a98d7b62046797097c012
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies. The framework defines a simple role based security policy and an URL security -- policy intended to provide security in web applications. The security policy manager reads -- some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components (yellow) are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance. Additional security policy context can be added depending on -- the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- @include security-permissions.ads -- @include security-openid.ads -- @include security-oauth.ads -- @include security-contexts.ads -- @include security-controllers.ads package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
1c6fca89a5e767ed68f5164b769525d74b3fda1e
src/security-auth-openid.ads
src/security-auth-openid.ads
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == OpenID == -- The <b>Security.OpenID</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The OpenID manager must be declared and configured. -- -- Mgr : Security.OpenID.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the OpenID realm and set the OpenID return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify"); -- -- After this initialization, the OpenID manager can be used in the authentication process. -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.OpenID.End_Point; -- Assoc : constant Security.OpenID.Association_Access := new Security.OpenID.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : OpenID.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Auth); -- if Security.OpenID.Get_Status (Auth) = Security.OpenID.AUTHENTICATED then ... -- Success. -- -- === Principal creation === -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.OpenID.Principal_Access := Security.OpenID.Create_Principal (Auth); -- private package Security.Auth.OpenID is -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is new Security.Auth.Manager with private; -- Initialize the authentication realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private type Manager is new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; end record; end Security.Auth.OpenID;
----------------------------------------------------------------------- -- security-openid -- OpenID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- === OpenID Configuration == -- The Open ID provider needs the following configuration parameters: -- -- openid.realm The OpenID realm parameter passed in the authentication URL. -- openid.callback_url The OpenID return_to parameter. -- private package Security.Auth.OpenID is -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is new Security.Auth.Manager with private; -- Initialize the OpenID authentication realm. Get the <tt>openid.realm</tt> -- and <tt>openid.callback_url</tt> parameters to configure the realm. overriding procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- Read the XRDS document from the URI and initialize the OpenID provider end point. -- (See OpenID Section 7.3 Discovery) overriding procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) overriding procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. overriding function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result overriding procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private type Manager is new Security.Auth.Manager with record Return_To : Unbounded_String; Realm : Unbounded_String; end record; end Security.Auth.OpenID;
Document the OpenID configuration parameters
Document the OpenID configuration parameters
Ada
apache-2.0
Letractively/ada-security
f45c3d3304db62c7faf15935c66b3e00331152f8
tools/druss-commands-ping.ads
tools/druss-commands-ping.ads
----------------------------------------------------------------------- -- druss-commands-ping -- Ping devices from the gateway -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Druss.Commands.Ping is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type); -- Execute a ping from the gateway to each device. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in Command_Type; Context : in out Context_Type); end Druss.Commands.Ping;
----------------------------------------------------------------------- -- druss-commands-ping -- Ping devices from the gateway -- Copyright (C) 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Druss.Commands.Ping is type Command_Type is new Druss.Commands.Drivers.Command_Type with null record; procedure Do_Ping (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type); -- Execute a ping from the gateway to each device. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Context : in out Context_Type); end Druss.Commands.Ping;
Change Help command to accept in out command
Change Help command to accept in out command
Ada
apache-2.0
stcarrez/bbox-ada-api
aeb988b4d5488677e5138a3f605074b8c5173dc7
awa/plugins/awa-storages/src/awa-storages-stores-files.adb
awa/plugins/awa-storages/src/awa-storages-stores-files.adb
----------------------------------------------------------------------- -- awa-storages-stores-files -- File system store -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Directories; with Interfaces; with Util.Files; with Util.Encoders; with Util.Encoders.Base64; package body AWA.Storages.Stores.Files is -- ------------------------------ -- Create a file storage service and use the <tt>Root</tt> directory to store the files. -- ------------------------------ function Create_File_Store (Root : in String) return Store_Access is Result : constant File_Store_Access := new File_Store '(Len => Root'Length, Root => Root); begin return Result.all'Access; end Create_File_Store; -- ------------------------------ -- Build a path where the file store represented by <tt>Store</tt> is saved. -- ------------------------------ function Get_Path (Storage : in File_Store; Store : in AWA.Storages.Models.Storage_Ref'Class) return String is use Interfaces; use type Ada.Streams.Stream_Element_Offset; T : Util.Encoders.Base64.Encoder; Buffer : Ada.Streams.Stream_Element_Array (1 .. 10); R : Ada.Streams.Stream_Element_Array (1 .. 32); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Pos : Positive := 1; Res : String (1 .. 16 + 5); Workspace_Id : constant ADO.Identifier := Store.Get_Workspace.Get_Id; begin Util.Encoders.Encode_LEB128 (Buffer, Buffer'First, Unsigned_64 (Workspace_Id), Last); Util.Encoders.Encode_LEB128 (Buffer, Last, Unsigned_64 (Store.Get_Id), Last); T.Transform (Data => Buffer (1 .. Last), Into => R, Last => Last, Encoded => Encoded); for I in 1 .. Last loop Res (Pos) := Character'Val (R (I)); Pos := Pos + 1; if (I mod 2) = 0 and I /= Last then Res (Pos) := '/'; Pos := Pos + 1; end if; end loop; return Util.Files.Compose (Storage.Root, Res (1 .. Pos - 1)); end Get_Path; -- ------------------------------ -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. -- ------------------------------ procedure Save (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (Into); Dir : constant String := Ada.Directories.Containing_Directory (Store); begin Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Path, Target_Name => Store, Form => "all"); end Save; procedure Load (Storage : in File_Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out Storage_File) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); begin Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store); end Load; -- ------------------------------ -- Create a storage -- ------------------------------ procedure Create (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is pragma Unreferenced (Storage); Store : constant String := Storage.Get_Path (From); Dir : constant String := Ada.Directories.Containing_Directory (Store); begin Ada.Directories.Create_Path (Dir); Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store); end Create; -- ------------------------------ -- Delete the content associate with the storage represented by `From`. -- ------------------------------ procedure Delete (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); begin if Ada.Directories.Exists (Store) then Ada.Directories.Delete_File (Store); end if; end Delete; end AWA.Storages.Stores.Files;
----------------------------------------------------------------------- -- awa-storages-stores-files -- File system store -- Copyright (C) 2012, 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.Streams; with Ada.Directories; with Interfaces; with Util.Files; with Util.Log.Loggers; with Util.Encoders; with Util.Encoders.Base64; package body AWA.Storages.Stores.Files is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Stores.Files"); -- ------------------------------ -- Create a file storage service and use the <tt>Root</tt> directory to store the files. -- ------------------------------ function Create_File_Store (Root : in String) return Store_Access is Result : constant File_Store_Access := new File_Store '(Len => Root'Length, Root => Root); begin return Result.all'Access; end Create_File_Store; -- ------------------------------ -- Build a path where the file store represented by <tt>Store</tt> is saved. -- ------------------------------ function Get_Path (Storage : in File_Store; Store : in AWA.Storages.Models.Storage_Ref'Class) return String is use Interfaces; use type Ada.Streams.Stream_Element_Offset; T : Util.Encoders.Base64.Encoder; Buffer : Ada.Streams.Stream_Element_Array (1 .. 10); R : Ada.Streams.Stream_Element_Array (1 .. 32); Last : Ada.Streams.Stream_Element_Offset; Encoded : Ada.Streams.Stream_Element_Offset; Pos : Positive := 1; Res : String (1 .. 16 + 5); Workspace_Id : constant ADO.Identifier := Store.Get_Workspace.Get_Id; begin Util.Encoders.Encode_LEB128 (Buffer, Buffer'First, Unsigned_64 (Workspace_Id), Last); Util.Encoders.Encode_LEB128 (Buffer, Last, Unsigned_64 (Store.Get_Id), Last); T.Transform (Data => Buffer (1 .. Last), Into => R, Last => Last, Encoded => Encoded); for I in 1 .. Last loop Res (Pos) := Character'Val (R (I)); Pos := Pos + 1; if (I mod 2) = 0 and I /= Last then Res (Pos) := '/'; Pos := Pos + 1; end if; end loop; return Util.Files.Compose (Storage.Root, Res (1 .. Pos - 1)); end Get_Path; -- ------------------------------ -- Save the file represented by the `Path` variable into a store and associate that -- content with the storage reference represented by `Into`. -- ------------------------------ procedure Save (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (Into); Dir : constant String := Ada.Directories.Containing_Directory (Store); begin Log.Info ("Storage save {0} to {1}", Path, Store); Ada.Directories.Create_Path (Dir); Ada.Directories.Copy_File (Source_Name => Path, Target_Name => Store, Form => "all"); end Save; procedure Load (Storage : in File_Store; Session : in out ADO.Sessions.Session'Class; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out Storage_File) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); begin Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store); end Load; -- ------------------------------ -- Create a storage -- ------------------------------ procedure Create (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; From : in AWA.Storages.Models.Storage_Ref'Class; Into : in out AWA.Storages.Storage_File) is pragma Unreferenced (Storage); Store : constant String := Storage.Get_Path (From); Dir : constant String := Ada.Directories.Containing_Directory (Store); begin Log.Info ("Storage create {0}", Store); Ada.Directories.Create_Path (Dir); Into.Path := Ada.Strings.Unbounded.To_Unbounded_String (Store); end Create; -- ------------------------------ -- Delete the content associate with the storage represented by `From`. -- ------------------------------ procedure Delete (Storage : in File_Store; Session : in out ADO.Sessions.Master_Session; From : in out AWA.Storages.Models.Storage_Ref'Class) is pragma Unreferenced (Session); Store : constant String := Storage.Get_Path (From); begin if Ada.Directories.Exists (Store) then Log.Info ("Storage delete {0}", Store); Ada.Directories.Delete_File (Store); end if; end Delete; end AWA.Storages.Stores.Files;
Add some log message for trouble shotting storage issues
Add some log message for trouble shotting storage issues
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b2753503cde2b68490c698139108aa1e11d0fb62
src/atlas-applications.ads
src/atlas-applications.ads
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Filters.Cache_Control; with ASF.Servlets.Measures; with ASF.Security.Servlets; with ASF.Converters.Sizes; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Wikis.Modules; with AWA.Wikis.Previews; with AWA.Jobs.Modules; with AWA.Counters.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Comments.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; with Atlas.Reviews.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- 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_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; No_Cache : aliased ASF.Filters.Cache_Control.Cache_Control_Filter; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Size_Converter : aliased ASF.Converters.Sizes.Size_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Job_Module : aliased AWA.Jobs.Modules.Job_Module; Storage_Module : aliased AWA.Storages.Modules.Storage_Module; Image_Module : aliased AWA.Images.Modules.Image_Module; Vote_Module : aliased AWA.Votes.Modules.Vote_Module; Question_Module : aliased AWA.Questions.Modules.Question_Module; Tag_Module : aliased AWA.Tags.Modules.Tag_Module; Comment_Module : aliased AWA.Comments.Modules.Comment_Module; Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module; Preview_Module : aliased AWA.Wikis.Previews.Preview_Module; Counter_Module : aliased AWA.Counters.Modules.Counter_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; Review_Module : aliased Atlas.Reviews.Modules.Review_Module; end record; end Atlas.Applications;
----------------------------------------------------------------------- -- atlas -- atlas applications ----------------------------------------------------------------------- -- Copyright (C) 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Filters.Dump; with ASF.Filters.Cache_Control; with ASF.Servlets.Measures; with ASF.Security.Servlets; with ASF.Converters.Sizes; with ASF.Applications; with AWA.Users.Servlets; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Applications; with AWA.Workspaces.Modules; with AWA.Storages.Modules; with AWA.Images.Modules; with AWA.Questions.Modules; with AWA.Wikis.Modules; with AWA.Wikis.Previews; with AWA.Jobs.Modules; with AWA.Counters.Modules; with AWA.Votes.Modules; with AWA.Tags.Modules; with AWA.Comments.Modules; with AWA.Services.Filters; with AWA.Converters.Dates; with Atlas.Microblog.Modules; with Atlas.Reviews.Modules; package Atlas.Applications is CONFIG_PATH : constant String := "/atlas"; CONTEXT_PATH : constant String := "/atlas"; ATLAS_NS_URI : aliased constant String := "http://code.google.com/p/ada-awa/atlas"; -- 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_Gravatar_Link (Email : in String) return String; -- EL function to convert an Email address to a Gravatar image. function To_Gravatar_Link (Email : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object; type Application is new AWA.Applications.Application with private; type Application_Access is access all Application'Class; -- Initialize the application. procedure Initialize (App : in Application_Access; Config : in ASF.Applications.Config); -- Initialize the ASF components provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the component factories used by the application. overriding procedure Initialize_Components (App : in out Application); -- Initialize the servlets provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application servlets. overriding procedure Initialize_Servlets (App : in out Application); -- Initialize the filters provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the application filters. overriding procedure Initialize_Filters (App : in out Application); -- Initialize the AWA modules provided by the application. -- This procedure is called by <b>Initialize</b>. -- It should register the modules used by the application. overriding procedure Initialize_Modules (App : in out Application); private type Application is new AWA.Applications.Application with record Self : Application_Access; -- Application servlets and filters (add new servlet and filter instances here). Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; No_Cache : aliased ASF.Filters.Cache_Control.Cache_Control_Filter; -- Authentication servlet and filter. Auth : aliased ASF.Security.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; -- Converters shared by web requests. Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; Size_Converter : aliased ASF.Converters.Sizes.Size_Converter; -- The application modules. User_Module : aliased AWA.Users.Modules.User_Module; Workspace_Module : aliased AWA.Workspaces.Modules.Workspace_Module; Blog_Module : aliased AWA.Blogs.Modules.Blog_Module; Mail_Module : aliased AWA.Mail.Modules.Mail_Module; Job_Module : aliased AWA.Jobs.Modules.Job_Module; Storage_Module : aliased AWA.Storages.Modules.Storage_Module; Image_Module : aliased AWA.Images.Modules.Image_Module; Vote_Module : aliased AWA.Votes.Modules.Vote_Module; Question_Module : aliased AWA.Questions.Modules.Question_Module; Tag_Module : aliased AWA.Tags.Modules.Tag_Module; Comment_Module : aliased AWA.Comments.Modules.Comment_Module; Wiki_Module : aliased AWA.Wikis.Modules.Wiki_Module; Preview_Module : aliased AWA.Wikis.Previews.Preview_Module; Counter_Module : aliased AWA.Counters.Modules.Counter_Module; Microblog_Module : aliased Atlas.Microblog.Modules.Microblog_Module; Review_Module : aliased Atlas.Reviews.Modules.Review_Module; end record; end Atlas.Applications;
Update the Initialize procedure to pass a Config property object
Update the Initialize procedure to pass a Config property object
Ada
apache-2.0
stcarrez/atlas
cb37eb555baad6309f5d5b286bd644e8dd5d894e
src/mysql/ado-drivers-connections-mysql.adb
src/mysql/ado-drivers-connections-mysql.adb
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Finalization; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- This is a little bit overkill but this is portable. We must call the 'mysql_thread_end' -- operation before a task/thread terminates. The only way to do it is to setup a task -- attribute which an object that has a finalization procedure. -- -- The task cleaner attribute is set on tasks that call the 'mysql_connect' operation only. type Mysql_Task_Cleaner is new Ada.Finalization.Controlled with null record; -- Invoke the 'mysql_task_end' to release the storage allocated by mysql for the current task. overriding procedure Finalize (Object : in out Mysql_Task_Cleaner); Cleaner : Mysql_Task_Cleaner; package Mysql_Task_Attribute is new Ada.Task_Attributes (Mysql_Task_Cleaner, Cleaner); -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Result : char; begin Result := mysql_commit (Database.Server); if Result /= nul then raise DB_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is Result : char; begin Result := mysql_rollback (Database.Server); if Result /= nul then raise DB_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin null; end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Error ("Database connection is not open"); end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin Log.Info ("Closing connection {0}", Database.Name); if Database.Server /= null then mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}", Database.Name); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); Server : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Database : constant Database_Connection_Access := new Database_Connection; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Connecting to {0}:{1}", To_String (Config.Server), To_String (Config.Database)); Log.Debug ("user={0} password={1}", Config.Get_Property ("user"), Config.Get_Property ("password")); Connection := mysql_init (null); Mysql_Task_Attribute.Set_Value (Cleaner); Database.Server := mysql_real_connect (Connection, ADO.C.To_C (Server), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Database.Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message); mysql_close (Connection); raise Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; Database.Name := Config.Database; Database.Count := 1; Result := Database.all'Access; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; -- ------------------------------ -- Invoke the 'mysql_task_end' to release the storage allocated by mysql for the current task. -- ------------------------------ overriding procedure Finalize (Object : in out Mysql_Task_Cleaner) is pragma Unreferenced (Object); begin mysql_thread_end; end Finalize; end ADO.Drivers.Connections.Mysql;
----------------------------------------------------------------------- -- ADO Mysql Database -- MySQL Database connections -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Mysql; with ADO.C; with Mysql.Lib; use Mysql.Lib; package body ADO.Drivers.Connections.Mysql is use ADO.Statements.Mysql; use Util.Log; use Interfaces.C; pragma Linker_Options (MYSQL_LIB_NAME); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Mysql"); Driver_Name : aliased constant String := "mysql"; Driver : aliased Mysql_Driver; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return ADO.Drivers.Connections.Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin if Database.Autocommit then Database.Execute ("set autocommit=0"); Database.Autocommit := False; end if; Database.Execute ("start transaction;"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is Result : char; begin Result := mysql_commit (Database.Server); if Result /= nul then raise DB_Error with "Cannot commit transaction"; end if; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is Result : char; begin Result := mysql_rollback (Database.Server); if Result /= nul then raise DB_Error with "Cannot rollback transaction"; end if; end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin null; end Load_Schema; -- ------------------------------ -- Execute a simple SQL statement -- ------------------------------ procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = null then Log.Error ("Database connection is not open"); end if; Result := Mysql_Query (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", int'Image (Result)); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin Log.Info ("Closing connection {0}", Database.Name); if Database.Server /= null then mysql_close (Database.Server); Database.Server := null; end if; end Close; -- ------------------------------ -- Releases the mysql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}", Database.Name); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- mysql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Mysql_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); Server : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Server); Name : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Database); Login : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_Property ("user")); Password : constant ADO.C.String_Ptr := C.To_String_Ptr (Config.Get_Property ("password")); Socket : ADO.C.String_Ptr; Port : unsigned := unsigned (Config.Port); Flags : constant unsigned_long := 0; Connection : Mysql_Access; Socket_Path : constant String := Config.Get_Property ("socket"); Database : constant Database_Connection_Access := new Database_Connection; begin if Socket_Path /= "" then ADO.C.Set_String (Socket, Socket_Path); end if; if Port = 0 then Port := 3306; end if; Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), To_String (Config.Server), To_String (Config.Database)); Log.Debug ("user={0} password={1}", Config.Get_Property ("user"), Config.Get_Property ("password")); Connection := mysql_init (null); Database.Server := mysql_real_connect (Connection, ADO.C.To_C (Server), ADO.C.To_C (Login), ADO.C.To_C (Password), ADO.C.To_C (Name), Port, ADO.C.To_C (Socket), Flags); if Database.Server = null then declare Message : constant String := Strings.Value (Mysql_Error (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.URI), Message); mysql_close (Connection); raise Connection_Error with "Cannot connect to mysql server: " & Message; end; end if; Database.Name := Config.Database; Database.Count := 1; Result := Database.all'Access; end Create_Connection; -- ------------------------------ -- Initialize the Mysql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing mysql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Mysql driver. -- ------------------------------ overriding procedure Finalize (D : in out Mysql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the mysql driver"); mysql_server_end; end Finalize; end ADO.Drivers.Connections.Mysql;
Revert r326 because Ada task attribute cleaner is not executed by the thread which sets the TLS data. Hence, invoking mysql_thread_end is done but not by the good thread. Fixed the issue by patching libmysqlclient (See MySQL bug http://bugs.mysql.com/bug.php?id=66740)
Revert r326 because Ada task attribute cleaner is not executed by the thread which sets the TLS data. Hence, invoking mysql_thread_end is done but not by the good thread. Fixed the issue by patching libmysqlclient (See MySQL bug http://bugs.mysql.com/bug.php?id=66740)
Ada
apache-2.0
Letractively/ada-ado
f7508c37943da99489977c1d0500705c3fb3ded2
src/util-serialize-io-csv.adb
src/util-serialize-io-csv.adb
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 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.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character) is begin Stream.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Enable or disable the double quotes by default for strings. -- ------------------------------ procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean) is begin Stream.Quote := Enable; end Set_Quotes; -- ------------------------------ -- 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) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ('"'); end if; for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; if Stream.Quote then Stream.Write ('"'); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ("""null"""); else Stream.Write ("null"); end if; when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; -- Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); -- Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (Stream.Separator); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- 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 is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- 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) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Handler.Sink.Finish_Object (""); else Handler.Sink.Start_Array (""); end if; Handler.Sink.Start_Object (""); end if; Handler.Row := Row; Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value)); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- 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) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- 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) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; -- Context : Element_Context_Access; begin -- Context_Stack.Push (Handler.Stack); -- Context := Context_Stack.Current (Handler.Stack); -- Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; Handler.Sink := Sink'Unchecked_Access; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; Handler.Sink := null; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); -- Context_Stack.Pop (Handler.Stack); Handler.Sink := null; return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 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.Characters.Latin_1; with Ada.IO_Exceptions; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character) is begin Stream.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Enable or disable the double quotes by default for strings. -- ------------------------------ procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean) is begin Stream.Quote := Enable; end Set_Quotes; -- ------------------------------ -- 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) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ('"'); end if; for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; if Stream.Quote then Stream.Write ('"'); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ("""null"""); else Stream.Write ("null"); end if; when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; -- Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); -- Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (Stream.Separator); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- 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 is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- 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) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Handler.Sink.Finish_Object ("", Handler); else Handler.Sink.Start_Array ("", Handler); end if; Handler.Sink.Start_Object ("", Handler); end if; Handler.Row := Row; Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- 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) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- 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) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Buffered_Stream'Class; Sink : in out Reader'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; -- Context : Element_Context_Access; begin -- Context_Stack.Push (Handler.Stack); -- Context := Context_Stack.Current (Handler.Stack); -- Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access; if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; Handler.Sink := Sink'Unchecked_Access; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; Handler.Sink := null; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); -- Context_Stack.Pop (Handler.Stack); Handler.Sink := null; return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
Add the Handler object for the Logger instance to be used by Reader interface
Add the Handler object for the Logger instance to be used by Reader interface
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f75f319e8d05fe268110be14d5bd1c41949d36d6
src/util-streams-files.ads
src/util-streams-files.ads
----------------------------------------------------------------------- -- util-streams-files -- File Stream utilities -- Copyright (C) 2010, 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.Finalization; with Ada.Streams.Stream_IO; -- == File streams == -- The <tt>Util.Streams.Files</tt> package provides input and output streams that access -- files on top of the Ada <tt>Stream_IO</tt> standard package. package Util.Streams.Files is -- ----------------------- -- File stream -- ----------------------- -- The <b>File_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type File_Stream is limited new Output_Stream and Input_Stream with private; -- Open the file and initialize the stream for reading or writing. procedure Open (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Create the file and initialize the stream for writing. procedure Create (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Close the stream. overriding procedure Close (Stream : in out File_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out File_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out File_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Streams; type File_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Ada.Streams.Stream_IO.File_Type; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out File_Stream); end Util.Streams.Files;
----------------------------------------------------------------------- -- util-streams-files -- File Stream utilities -- Copyright (C) 2010, 2013, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Streams.Stream_IO; -- == File streams == -- The <tt>Util.Streams.Files</tt> package provides input and output streams that access -- files on top of the Ada <tt>Stream_IO</tt> standard package. package Util.Streams.Files is -- ----------------------- -- File stream -- ----------------------- -- The <b>File_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type File_Stream is limited new Output_Stream and Input_Stream with private; -- Open the file and initialize the stream for reading or writing. procedure Open (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Create the file and initialize the stream for writing. procedure Create (Stream : in out File_Stream; Mode : in Ada.Streams.Stream_IO.File_Mode; Name : in String := ""; Form : in String := ""); -- Close the stream. overriding procedure Close (Stream : in out File_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out File_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out File_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); private type File_Stream is limited new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : Ada.Streams.Stream_IO.File_Type; end record; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out File_Stream); end Util.Streams.Files;
Remove unused use Ada.Streams clause reported by GNAT 2018
Remove unused use Ada.Streams clause reported by GNAT 2018
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b7de7d710da9d351ec73c651f52d245471367bcd
regtests/el-objects-time-tests.adb
regtests/el-objects-time-tests.adb
----------------------------------------------------------------------- -- EL.Objects.Time.Tests - Testsuite time objects -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Calendar.Formatting; with Util.Log.Loggers; with Util.Tests; package body EL.Objects.Time.Tests is use Ada.Calendar; use Util.Log; use Util.Tests; LOG : constant Util.Log.Loggers.Logger := Loggers.Create ("Tests"); -- ------------------------------ -- Test evaluation of expression using a bean -- ------------------------------ procedure Test_Time_Object (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); begin T.Assert (Is_Null (V) = False, "Object holding a time value must not be null"); T.Assert (Is_Empty (V) = False, "Object holding a time value must not be empty"); T.Assert (Get_Type (V) = TYPE_TIME, "Object holding a time value must be TYPE_TIME"); T.Assert (C = To_Time (V), "Invalid time returned by To_Time"); end Test_Time_Object; -- ------------------------------ -- Test time to string conversion -- ------------------------------ procedure Test_Time_To_String (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); S : constant EL.Objects.Object := Cast_String (V); V2 : constant EL.Objects.Object := Cast_Time (S); begin -- Both 3 values should be the same. LOG.Info ("Time S : {0}", To_String (S)); LOG.Info ("Time V : {0}", To_String (V)); LOG.Info ("Time V2: {0}", To_String (V2)); Assert_Equals (T, To_String (S), To_String (V), "Invalid time conversion (V)"); Assert_Equals (T, To_String (S), To_String (V2), "Invalid time conversion (V2)"); -- The Cast_String looses accuracy so V and V2 may not be equal. T.Assert (V >= V2, "Invalid time to string conversion"); -- Check the time value taking into account the 1 sec accuracy that was lost. T.Assert (C >= To_Time (V2), "Invalid time returned by To_Time (T > expected)"); T.Assert (C < To_Time (V2) + 1.0, "Invalid time returned by To_Time (T + 1 < expected)"); end Test_Time_To_String; -- ------------------------------ -- Test time add and subtract -- ------------------------------ procedure Test_Time_Add (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); Dt : constant EL.Objects.Object := To_Object (Integer (10)); V2 : constant EL.Objects.Object := V + Dt; V3 : constant EL.Objects.Object := V2 - Dt; begin T.Assert (V3 = V, "Adding and substracting 10 seconds should result in the same time"); T.Assert (V2 > V, "Invalid comparison for time"); T.Assert (V3 < V2, "Invalid comparison for time"); end Test_Time_Add; package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Caller.Add_Test (Suite, "Test EL.Objects.Time.To_Object - Is_Null, Is_Empty, Get_Type", Test_Time_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_Object - To_Time", Test_Time_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_String - Cast_Time", Test_Time_To_String'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_String - Cast_Time", Test_Time_Add'Access); end Add_Tests; end EL.Objects.Time.Tests;
----------------------------------------------------------------------- -- EL.Objects.Time.Tests - Testsuite time objects -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Ada.Calendar.Formatting; with Util.Log.Loggers; with Util.Tests; package body EL.Objects.Time.Tests is use Ada.Calendar; use Util.Log; use Util.Tests; LOG : constant Util.Log.Loggers.Logger := Loggers.Create ("Tests"); -- ------------------------------ -- Test evaluation of expression using a bean -- ------------------------------ procedure Test_Time_Object (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); begin T.Assert (Is_Null (V) = False, "Object holding a time value must not be null"); T.Assert (Is_Empty (V) = False, "Object holding a time value must not be empty"); T.Assert (Get_Type (V) = TYPE_TIME, "Object holding a time value must be TYPE_TIME"); T.Assert (C = To_Time (V), "Invalid time returned by To_Time"); end Test_Time_Object; -- ------------------------------ -- Test time to string conversion -- ------------------------------ procedure Test_Time_To_String (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); S : constant EL.Objects.Object := Cast_String (V); V2 : constant EL.Objects.Object := Cast_Time (S); begin -- Both 3 values should be the same. LOG.Info ("Time S : {0}", To_String (S)); LOG.Info ("Time V : {0}", To_String (V)); LOG.Info ("Time V2: {0}", To_String (V2)); Assert_Equals (T, To_String (S), To_String (V), "Invalid time conversion (V)"); Assert_Equals (T, To_String (S), To_String (V2), "Invalid time conversion (V2)"); -- The Cast_String looses accuracy so V and V2 may not be equal. T.Assert (V >= V2, "Invalid time to string conversion"); -- Check the time value taking into account the 1 sec accuracy that was lost. T.Assert (C >= To_Time (V2), "Invalid time returned by To_Time (T > expected)"); T.Assert (C < To_Time (V2) + 1.0, "Invalid time returned by To_Time (T + 1 < expected)"); end Test_Time_To_String; -- ------------------------------ -- Test time add and subtract -- ------------------------------ procedure Test_Time_Add (T : in out Test) is C : constant Ada.Calendar.Time := Ada.Calendar.Clock; V : constant EL.Objects.Object := To_Object (C); Dt : constant EL.Objects.Object := To_Object (Integer (10)); V2 : constant EL.Objects.Object := V + Dt; V3 : constant EL.Objects.Object := V2 - Dt; begin T.Assert (V3 = V, "Adding and substracting 10 seconds should result in the same time"); T.Assert (V2 > V, "Invalid comparison for time"); T.Assert (V3 < V2, "Invalid comparison for time"); end Test_Time_Add; package Caller is new Util.Test_Caller (Test, "EL.Objects.Time"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin -- Test_Bean verifies several methods. Register several times -- to enumerate what is tested. Caller.Add_Test (Suite, "Test EL.Objects.Time.To_Object - Is_Null, Is_Empty, Get_Type", Test_Time_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_Object - To_Time", Test_Time_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_String - Cast_Time", Test_Time_To_String'Access); Caller.Add_Test (Suite, "Test EL.Objects.Time.To_String - Cast_Time", Test_Time_Add'Access); end Add_Tests; end EL.Objects.Time.Tests;
Use the test name EL.Objects.Time
Use the test name EL.Objects.Time
Ada
apache-2.0
Letractively/ada-el
eaea1ced493a364a3cca60f8aeef2bfa9503ae78
src/gen-commands-info.adb
src/gen-commands-info.adb
----------------------------------------------------------------------- -- gen-commands-info -- Collect and give information about the project -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Gen.Utils; with Gen.Utils.GNAT; with Gen.Model.Projects; with Util.Strings.Sets; with Util.Files; package body Gen.Commands.Info is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector); procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean); procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition); procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition); procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count); procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition); List : Gen.Utils.String_List.Vector; Names : Util.Strings.Sets.Set; procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector) is procedure Add_Model_Dir (Base_Dir : in String; Dir : in String); procedure Add_Model_Dir (Base_Dir : in String; Dir : in String) is Path : constant String := Util.Files.Compose (Base_Dir, Dir); begin if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then Result.Append (Path); end if; end Add_Model_Dir; Iter : Gen.Utils.String_List.Cursor := List.First; begin while Gen.Utils.String_List.Has_Element (Iter) loop declare Path : constant String := Gen.Utils.String_List.Element (Iter); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Add_Model_Dir (Dir, "db"); Add_Model_Dir (Dir, "db/regtests"); Add_Model_Dir (Dir, "db/samples"); end; Gen.Utils.String_List.Next (Iter); end loop; end Collect_Directories; procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean) is pragma Unreferenced (Name); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (File); Done := False; end Print_Model_File; -- ------------------------------ -- Print the list of GNAT projects used by the main project. -- ------------------------------ procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is use Gen.Utils.GNAT; Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First; Info : Project_Info; begin if Project_Info_Vectors.Has_Element (Iter) then Ada.Text_IO.Put_Line ("GNAT project files:"); while Project_Info_Vectors.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Info := Project_Info_Vectors.Element (Iter); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path)); Project_Info_Vectors.Next (Iter); end loop; end if; end Print_GNAT_Projects; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := Project.Modules.First; Ref : Model.Projects.Project_Reference; begin if Project_Vectors.Has_Element (Iter) then Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put_Line ("Dynamo plugins:"); while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name)); Ada.Text_IO.Set_Col (Indent + 30); if Ref.Project /= null then Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path)); else Ada.Text_IO.Put_Line ("?"); end if; Project_Vectors.Next (Iter); end loop; Iter := Project.Modules.First; while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then declare Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name); begin Ada.Text_IO.Set_Col (Indent); if Names.Contains (Name) then Ada.Text_IO.Put_Line ("!! " & Name); else Names.Insert (Name); Ada.Text_IO.Put_Line ("== " & Name); Print_Modules (Ref.Project.all, Indent + 4); Names.Delete (Name); end if; end; end if; Project_Vectors.Next (Iter); end loop; end if; end Print_Modules; -- ------------------------------ -- Print the list of Dynamo projects used by the main project. -- ------------------------------ procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First; begin if Gen.Utils.String_List.Has_Element (Iter) then Ada.Text_IO.Put_Line ("Dynamo project files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Gen.Utils.String_List.Next (Iter); end loop; end if; end Print_Dynamo_Projects; procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is begin Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project)); Print_Dynamo_Projects (Project); Print_Modules (Project, 1); declare Model_Dirs : Gen.Utils.String_List.Vector; begin Collect_Directories (List, Model_Dirs); declare Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First; begin Ada.Text_IO.Put_Line ("ADO model files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Util.Files.Iterate_Files_Path (Pattern => "*.xml", Path => Gen.Utils.String_List.Element (Iter), Process => Print_Model_File'Access); Gen.Utils.String_List.Next (Iter); end loop; end; end; end Print_Project; begin Generator.Read_Project ("dynamo.xml", True); Generator.Update_Project (Print_Project'Access); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); begin Ada.Text_IO.Put_Line ("info: Print information about the current project"); Ada.Text_IO.Put_Line ("Usage: info"); Ada.Text_IO.New_Line; end Help; end Gen.Commands.Info;
----------------------------------------------------------------------- -- gen-commands-info -- Collect and give information about the project -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Directories; with Gen.Utils; with Gen.Utils.GNAT; with Gen.Model.Projects; with Util.Strings.Sets; with Util.Files; package body Gen.Commands.Info is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector); procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean); procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition); procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition); procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count); procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition); List : Gen.Utils.String_List.Vector; Names : Util.Strings.Sets.Set; procedure Collect_Directories (List : in Gen.Utils.String_List.Vector; Result : out Gen.Utils.String_List.Vector) is procedure Add_Model_Dir (Base_Dir : in String; Dir : in String); procedure Add_Model_Dir (Base_Dir : in String; Dir : in String) is Path : constant String := Util.Files.Compose (Base_Dir, Dir); begin if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then Result.Append (Path); end if; end Add_Model_Dir; Iter : Gen.Utils.String_List.Cursor := List.First; begin while Gen.Utils.String_List.Has_Element (Iter) loop declare Path : constant String := Gen.Utils.String_List.Element (Iter); Dir : constant String := Ada.Directories.Containing_Directory (Path); begin Add_Model_Dir (Dir, "db"); Add_Model_Dir (Dir, "db/regtests"); Add_Model_Dir (Dir, "db/samples"); end; Gen.Utils.String_List.Next (Iter); end loop; end Collect_Directories; procedure Print_Model_File (Name : in String; File : in String; Done : out Boolean) is pragma Unreferenced (Name); begin Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (File); Done := False; end Print_Model_File; -- ------------------------------ -- Print the list of GNAT projects used by the main project. -- ------------------------------ procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is use Gen.Utils.GNAT; Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First; Info : Project_Info; begin if Project_Info_Vectors.Has_Element (Iter) then Ada.Text_IO.Put_Line ("GNAT project files:"); while Project_Info_Vectors.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Info := Project_Info_Vectors.Element (Iter); Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path)); Project_Info_Vectors.Next (Iter); end loop; end if; end Print_GNAT_Projects; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Project_List (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count; List : in Gen.Model.Projects.Project_Vectors.Vector) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := List.First; Ref : Model.Projects.Project_Reference; begin while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name)); Ada.Text_IO.Set_Col (Indent + 30); if Ref.Project /= null then Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path)); else Ada.Text_IO.Put_Line ("?"); end if; Project_Vectors.Next (Iter); end loop; end Print_Project_List; -- ------------------------------ -- Print the list of Dynamo modules -- ------------------------------ procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class; Indent : in Ada.Text_IO.Positive_Count) is use Gen.Model.Projects; use type Ada.Text_IO.Positive_Count; Iter : Project_Vectors.Cursor := Project.Modules.First; Ref : Model.Projects.Project_Reference; begin if not Project.Modules.Is_Empty then Ada.Text_IO.Set_Col (Indent); Ada.Text_IO.Put_Line ("Dynamo plugins:"); Print_Project_List (Project, Indent, Project.Modules); Print_Project_List (Project, Indent, Project.Dependencies); Iter := Project.Modules.First; while Project_Vectors.Has_Element (Iter) loop Ref := Project_Vectors.Element (Iter); if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then declare Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name); begin Ada.Text_IO.Set_Col (Indent); if Names.Contains (Name) then Ada.Text_IO.Put_Line ("!! " & Name); else Names.Insert (Name); Ada.Text_IO.Put_Line ("== " & Name); Print_Modules (Ref.Project.all, Indent + 4); Names.Delete (Name); end if; end; end if; Project_Vectors.Next (Iter); end loop; end if; end Print_Modules; -- ------------------------------ -- Print the list of Dynamo projects used by the main project. -- ------------------------------ procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First; begin if Gen.Utils.String_List.Has_Element (Iter) then Ada.Text_IO.Put_Line ("Dynamo project files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Gen.Utils.String_List.Next (Iter); end loop; end if; end Print_Dynamo_Projects; procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is begin Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project)); Print_Dynamo_Projects (Project); Print_Modules (Project, 1); declare Model_Dirs : Gen.Utils.String_List.Vector; begin Collect_Directories (List, Model_Dirs); declare Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First; begin Ada.Text_IO.Put_Line ("ADO model files:"); while Gen.Utils.String_List.Has_Element (Iter) loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter)); Util.Files.Iterate_Files_Path (Pattern => "*.xml", Path => Gen.Utils.String_List.Element (Iter), Process => Print_Model_File'Access); Gen.Utils.String_List.Next (Iter); end loop; end; end; end Print_Project; begin Generator.Read_Project ("dynamo.xml", True); Generator.Update_Project (Print_Project'Access); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); begin Ada.Text_IO.Put_Line ("info: Print information about the current project"); Ada.Text_IO.Put_Line ("Usage: info"); Ada.Text_IO.New_Line; end Help; end Gen.Commands.Info;
Print the dependencies of a dynamo plugin
Print the dependencies of a dynamo plugin
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
59d1118d0ad26d0c5e15af582e2c7c98cb812402
src/asf-views-nodes-jsf.ads
src/asf-views-nodes-jsf.ads
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Validators; -- The <b>ASF.Views.Nodes.Jsf</b> package implements various JSF Core Tag -- components which alter the component tree but don't need to create -- new UI components in the usual way. The following components are supported: -- -- <f:attribute name='...' value='...'/> -- <f:converter converterId='...'/> -- <f:validateXXX .../> -- <f:facet name='...'>...</f:facet> -- -- The <b>f:attribute</b>, <b>f:converter</b> and <b>f:validateXXX</b> tags don't create any -- component. The <b>f:facet</b> creates components that are inserted as a facet component -- in the component tree. package ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- The <b>Converter_Tag_Node</b> is created in the facelet tree when -- the <f:converter> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Converter_Tag_Node is new Views.Nodes.Tag_Node with private; type Converter_Tag_Node_Access is access all Converter_Tag_Node'Class; -- Create the Converter Tag function Create_Converter_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Validator Tag -- ------------------------------ -- The <b>Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateXXX> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Validator_Tag_Node is new Views.Nodes.Tag_Node with private; type Validator_Tag_Node_Access is access all Validator_Tag_Node'Class; -- Create the Validator Tag function Create_Validator_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- The <b>Range_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLongRange> element is found. -- The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Range_Validator_Tag_Node is new Validator_Tag_Node with private; type Range_Validator_Tag_Node_Access is access all Range_Validator_Tag_Node'Class; -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- The <b>Length_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLength> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Length_Validator_Tag_Node is new Validator_Tag_Node with private; type Length_Validator_Tag_Node_Access is access all Length_Validator_Tag_Node'Class; -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. function Create_Length_Validator_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Attribute Tag -- ------------------------------ -- The <b>Attribute_Tag_Node</b> is created in the facelet tree when -- the <f:attribute> element is found. When building the component tree, -- an attribute is added to the parent component. type Attribute_Tag_Node is new Views.Nodes.Tag_Node with private; type Attribute_Tag_Node_Access is access all Attribute_Tag_Node'Class; -- Create the Attribute Tag function Create_Attribute_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Facet Tag -- ------------------------------ -- The <b>Facet_Tag_Node</b> is created in the facelet tree when -- the <f:facet> element is found. After building the component tree, -- we have to add the component as a facet element of the parent component. -- type Facet_Tag_Node is new Views.Nodes.Tag_Node with private; type Facet_Tag_Node_Access is access all Facet_Tag_Node'Class; -- Create the Facet Tag function Create_Facet_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Metadata Tag -- ------------------------------ -- The <b>Metadata_Tag_Node</b> is created in the facelet tree when -- the <f:metadata> element is found. This special component is inserted as a special -- facet component on the UIView parent component. type Metadata_Tag_Node is new Views.Nodes.Tag_Node with private; type Metadata_Tag_Node_Access is access all Metadata_Tag_Node'Class; -- Create the Metadata Tag function Create_Metadata_Tag_Node (Name : Unbounded_String; Line : Views.Line_Info; Parent : Views.Nodes.Tag_Node_Access; Attributes : Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); private type Converter_Tag_Node is new Views.Nodes.Tag_Node with record Converter : EL.Objects.Object; end record; type Validator_Tag_Node is new Views.Nodes.Tag_Node with record Validator : EL.Objects.Object; end record; type Length_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Range_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Attribute_Tag_Node is new Views.Nodes.Tag_Node with record Attr : aliased Tag_Attribute; Attr_Name : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Facet_Tag_Node is new Views.Nodes.Tag_Node with record Facet_Name : Tag_Attribute_Access; end record; type Metadata_Tag_Node is new Views.Nodes.Tag_Node with null record; end ASF.Views.Nodes.Jsf;
----------------------------------------------------------------------- -- views.nodes.jsf -- JSF Core Tag Library -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Validators; -- The <b>ASF.Views.Nodes.Jsf</b> package implements various JSF Core Tag -- components which alter the component tree but don't need to create -- new UI components in the usual way. The following components are supported: -- -- <f:attribute name='...' value='...'/> -- <f:converter converterId='...'/> -- <f:validateXXX .../> -- <f:facet name='...'>...</f:facet> -- -- The <b>f:attribute</b>, <b>f:converter</b> and <b>f:validateXXX</b> tags don't create any -- component. The <b>f:facet</b> creates components that are inserted as a facet component -- in the component tree. package ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- The <b>Converter_Tag_Node</b> is created in the facelet tree when -- the <f:converter> element is found. When building the component tree, -- we have to find the <b>Converter</b> object and attach it to the -- parent component. The parent component must implement the <b>Value_Holder</b> -- interface. type Converter_Tag_Node is new Views.Nodes.Tag_Node with private; type Converter_Tag_Node_Access is access all Converter_Tag_Node'Class; -- Create the Converter Tag function Create_Converter_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. Get the specified converter and -- add it to the parent component. This operation does not create any -- new UIComponent. overriding procedure Build_Components (Node : access Converter_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Validator Tag -- ------------------------------ -- The <b>Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateXXX> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Validator_Tag_Node is new Views.Nodes.Tag_Node with private; type Validator_Tag_Node_Access is access all Validator_Tag_Node'Class; -- Create the Validator Tag function Create_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. procedure Get_Validator (Node : in Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- Get the specified validator and add it to the parent component. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Validator_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- The <b>Range_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLongRange> element is found. -- The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Range_Validator_Tag_Node is new Validator_Tag_Node with private; type Range_Validator_Tag_Node_Access is access all Range_Validator_Tag_Node'Class; -- Create the Range_Validator Tag function Create_Range_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the range validator. -- Returns in <b>Validator</b> the validator instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Range_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- The <b>Length_Validator_Tag_Node</b> is created in the facelet tree when -- the <f:validateLength> element is found. When building the component tree, -- we have to find the <b>Validator</b> object and attach it to the -- parent component. The parent component must implement the <b>Editable_Value_Holder</b> -- interface. type Length_Validator_Tag_Node is new Validator_Tag_Node with private; type Length_Validator_Tag_Node_Access is access all Length_Validator_Tag_Node'Class; -- Create the Length_Validator Tag. Verifies that the XML node defines -- the <b>minimum</b> or the <b>maximum</b> or both attributes. function Create_Length_Validator_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Get the validator instance that corresponds to the validator tag. -- Returns in <b>Validator</b> the instance if it exists and indicate -- in <b>Shared</b> whether it must be freed or not when the component is deleted. overriding procedure Get_Validator (Node : in Length_Validator_Tag_Node; Context : in out Contexts.Facelets.Facelet_Context'Class; Validator : out Validators.Validator_Access; Shared : out Boolean); -- ------------------------------ -- Attribute Tag -- ------------------------------ -- The <b>Attribute_Tag_Node</b> is created in the facelet tree when -- the <f:attribute> element is found. When building the component tree, -- an attribute is added to the parent component. type Attribute_Tag_Node is new Views.Nodes.Tag_Node with private; type Attribute_Tag_Node_Access is access all Attribute_Tag_Node'Class; -- Create the Attribute Tag function Create_Attribute_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the last child of the given parent. Calls recursively the -- method to create children. -- Adds the attribute to the component node. -- This operation does not create any new UIComponent. overriding procedure Build_Components (Node : access Attribute_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Facet Tag -- ------------------------------ -- The <b>Facet_Tag_Node</b> is created in the facelet tree when -- the <f:facet> element is found. After building the component tree, -- we have to add the component as a facet element of the parent component. -- type Facet_Tag_Node is new Views.Nodes.Tag_Node with private; type Facet_Tag_Node_Access is access all Facet_Tag_Node'Class; -- Create the Facet Tag function Create_Facet_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as -- the facet component of the given parent. Calls recursively the -- method to create children. overriding procedure Build_Components (Node : access Facet_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); -- ------------------------------ -- Metadata Tag -- ------------------------------ -- The <b>Metadata_Tag_Node</b> is created in the facelet tree when -- the <f:metadata> element is found. This special component is inserted as a special -- facet component on the UIView parent component. type Metadata_Tag_Node is new Views.Nodes.Tag_Node with private; type Metadata_Tag_Node_Access is access all Metadata_Tag_Node'Class; -- Create the Metadata Tag function Create_Metadata_Tag_Node (Binding : in Binding_Access; Line : in Views.Line_Info; Parent : in Views.Nodes.Tag_Node_Access; Attributes : in Views.Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access; -- Build the component tree from the tag node and attach it as a metadata information -- facet for the UIView parent component. overriding procedure Build_Components (Node : access Metadata_Tag_Node; Parent : in UIComponent_Access; Context : in out Contexts.Facelets.Facelet_Context'Class); private type Converter_Tag_Node is new Views.Nodes.Tag_Node with record Converter : EL.Objects.Object; end record; type Validator_Tag_Node is new Views.Nodes.Tag_Node with record Validator : EL.Objects.Object; end record; type Length_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Range_Validator_Tag_Node is new Validator_Tag_Node with record Minimum : Tag_Attribute_Access; Maximum : Tag_Attribute_Access; end record; type Attribute_Tag_Node is new Views.Nodes.Tag_Node with record Attr : aliased Tag_Attribute; Attr_Name : Tag_Attribute_Access; Value : Tag_Attribute_Access; end record; type Facet_Tag_Node is new Views.Nodes.Tag_Node with record Facet_Name : Tag_Attribute_Access; end record; type Metadata_Tag_Node is new Views.Nodes.Tag_Node with null record; end ASF.Views.Nodes.Jsf;
Change the Name parameter to a Binding access
Change the Name parameter to a Binding access
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
23f0e29931319e42b781932441f56af5a81b0a42
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; -- 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); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- 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; -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); 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; -- 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); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Move the To_Sock_Addr_Type and Usage operation to MAT.Targets
Move the To_Sock_Addr_Type and Usage operation to MAT.Targets
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0f1a48ef73d2b0a4daf95c5def62dc693b3abaa1
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 MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- 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); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); 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 MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- 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); -- Initialize the process targets by loading the MAT files. procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class); -- Symbol command. -- Load the symbols from the binary file. procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Threads command. -- Collect statistics about the threads and their allocation. procedure Threads_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String); end MAT.Commands;
Make the Threads_Command a public procedure
Make the Threads_Command a public procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a677f1aedc4f5ea2e135aee2120674bd5c963efe
mat/src/mat-consoles.adb
mat/src/mat-consoles.adb
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles is -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.Types.Hex_Image (Addr); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Field; -- ------------------------------ -- Format the size and print it for the given field. -- ------------------------------ procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size) is Value : constant String := MAT.Types.Target_Size'Image (Size); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Size; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val); end Print_Field; end MAT.Consoles;
Implement the Print_Field operation
Implement the Print_Field operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1098ba8fb8c330a81ef4b57f47e9198168784f17
awa/regtests/awa_command.adb
awa/regtests/awa_command.adb
----------------------------------------------------------------------- -- awa_command - Tests for AWA command -- 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.Commands; with Util.Tests; with AWA.Tests; with AWA.Commands.Drivers; with AWA.Commands.List; with AWA.Commands.Start; with AWA.Commands.Stop; with Servlet.Server; with ADO.Drivers; with AWA.Testsuite; procedure AWA_Command is package Server_Commands is new AWA.Commands.Drivers (Driver_Name => "awa", Container_Type => Servlet.Server.Container); package List_Command is new AWA.Commands.List (Server_Commands); package Start_Command is new AWA.Commands.Start (Server_Commands); package Stop_Command is new AWA.Commands.Stop (Server_Commands); App : aliased AWA.Tests.Test_Application; Context : AWA.Commands.Context_Type; Arguments : Util.Commands.Dynamic_Argument_List; Suite : Util.Tests.Access_Test_Suite := AWA.Testsuite.Suite; pragma Unreferenced (Suite); begin ADO.Drivers.Initialize; Server_Commands.WS.Register_Application ("/test", App'Unchecked_Access); Server_Commands.Run (Context, Arguments); exception when E : others => AWA.Commands.Print (Context, E); end AWA_Command;
----------------------------------------------------------------------- -- awa_command - Tests for AWA command -- 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.Commands; with Util.Tests; with AWA.Tests; with AWA.Commands.Drivers; with AWA.Commands.List; with AWA.Commands.Start; with AWA.Commands.Stop; with AWA.Commands.Info; with Servlet.Server; with ADO.Drivers; with AWA.Testsuite; procedure AWA_Command is package Server_Commands is new AWA.Commands.Drivers (Driver_Name => "awa", Container_Type => Servlet.Server.Container); package List_Command is new AWA.Commands.List (Server_Commands); package Start_Command is new AWA.Commands.Start (Server_Commands); package Stop_Command is new AWA.Commands.Stop (Server_Commands); package Info_Command is new AWA.Commands.Info (Server_Commands); App : aliased AWA.Tests.Test_Application; Context : AWA.Commands.Context_Type; Arguments : Util.Commands.Dynamic_Argument_List; Suite : Util.Tests.Access_Test_Suite := AWA.Testsuite.Suite; pragma Unreferenced (Suite); begin ADO.Drivers.Initialize; Server_Commands.WS.Register_Application ("/test", App'Unchecked_Access); Server_Commands.Run (Context, Arguments); exception when E : others => AWA.Commands.Print (Context, E); end AWA_Command;
Add the info command by instantiating the AWA.Commands.Info package
Add the info command by instantiating the AWA.Commands.Info package
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
501ca631044358c2f0ce4e16621ae8759a8aed7e
src/asf-servlets-mappers.ads
src/asf-servlets-mappers.ads
----------------------------------------------------------------------- -- asf-servlets-mappers -- Read servlet configuration files -- 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.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; with EL.Contexts; -- The <b>ASF.Servlets.Mappers</b> package defines an XML mapper that can be used -- to read the servlet configuration files. -- -- The servlet configuration used by ASF is a subset of the servlet deployment descriptor -- defined in JSR 315 - Java Servlet Specification Version 3.0. It includes: -- -- <ul> -- <li>Definition of filter mapping (<b>filter-mapping</b> tag)</li> -- <li>Definition of servlet mapping (<b>servlet-mapping</b> tag)</li> -- <li>Definition of context parameters (<b>context-param</b> tag)</li> -- <li>Definition of mime types (<b>mime-mapping</b> tag)</li> -- <li>Definition of error pages (<b>error-page</b> tag)</li> -- </ul> -- -- Other configurations are ignored by the mapper. -- -- Note: several JSR 315 configuration parameters do not makes sense in the ASF world -- because we cannot create a servlet or a filter through the configuration file. package ASF.Servlets.Mappers is type Servlet_Fields is (FILTER_MAPPING, FILTER_NAME, SERVLET_NAME, URL_PATTERN, SERVLET_MAPPING, CONTEXT_PARAM, PARAM_NAME, PARAM_VALUE, MIME_MAPPING, MIME_TYPE, EXTENSION, ERROR_PAGE, ERROR_CODE, LOCATION); -- ------------------------------ -- Servlet Config Reader -- ------------------------------ -- When reading and parsing the servlet configuration file, the <b>Servlet_Config</b> object -- is populated by calls through the <b>Set_Member</b> procedure. The data is -- collected and when the end of an element (FILTER_MAPPING, SERVLET_MAPPING, CONTEXT_PARAM) -- is reached, the definition is updated in the servlet registry. type Servlet_Config is limited record Filter_Name : Util.Beans.Objects.Object; Servlet_Name : Util.Beans.Objects.Object; URL_Pattern : Util.Beans.Objects.Object; Param_Name : Util.Beans.Objects.Object; Param_Value : Util.Beans.Objects.Object; Mime_Type : Util.Beans.Objects.Object; Extension : Util.Beans.Objects.Object; Error_Code : Util.Beans.Objects.Object; Location : Util.Beans.Objects.Object; Handler : Servlet_Registry_Access; Context : EL.Contexts.ELContext_Access; end record; type Servlet_Config_Access is access all Servlet_Config; -- Save in the servlet config object the value associated with the given field. -- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field -- is reached, insert the new configuration rule in the servlet registry. procedure Set_Member (N : in out Servlet_Config; Field : in Servlet_Fields; Value : in Util.Beans.Objects.Object); -- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>, -- <b>filter-mapping</b> and <b>servlet-mapping</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Handler : in Servlet_Registry_Access; Context : in EL.Contexts.ELContext_Access; package Reader_Config is Config : aliased Servlet_Config; end Reader_Config; private package Servlet_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Servlet_Config, Element_Type_Access => Servlet_Config_Access, Fields => Servlet_Fields, Set_Member => Set_Member); end ASF.Servlets.Mappers;
----------------------------------------------------------------------- -- asf-servlets-mappers -- Read servlet configuration files -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; with Util.Beans.Objects.Vectors; with EL.Contexts; -- The <b>ASF.Servlets.Mappers</b> package defines an XML mapper that can be used -- to read the servlet configuration files. -- -- The servlet configuration used by ASF is a subset of the servlet deployment descriptor -- defined in JSR 315 - Java Servlet Specification Version 3.0. It includes: -- -- <ul> -- <li>Definition of filter mapping (<b>filter-mapping</b> tag)</li> -- <li>Definition of servlet mapping (<b>servlet-mapping</b> tag)</li> -- <li>Definition of context parameters (<b>context-param</b> tag)</li> -- <li>Definition of mime types (<b>mime-mapping</b> tag)</li> -- <li>Definition of error pages (<b>error-page</b> tag)</li> -- </ul> -- -- Other configurations are ignored by the mapper. -- -- Note: several JSR 315 configuration parameters do not makes sense in the ASF world -- because we cannot create a servlet or a filter through the configuration file. package ASF.Servlets.Mappers is type Servlet_Fields is (FILTER_MAPPING, FILTER_NAME, SERVLET_NAME, URL_PATTERN, SERVLET_MAPPING, CONTEXT_PARAM, PARAM_NAME, PARAM_VALUE, MIME_MAPPING, MIME_TYPE, EXTENSION, ERROR_PAGE, ERROR_CODE, LOCATION); -- ------------------------------ -- Servlet Config Reader -- ------------------------------ -- When reading and parsing the servlet configuration file, the <b>Servlet_Config</b> object -- is populated by calls through the <b>Set_Member</b> procedure. The data is -- collected and when the end of an element (FILTER_MAPPING, SERVLET_MAPPING, CONTEXT_PARAM) -- is reached, the definition is updated in the servlet registry. type Servlet_Config is limited record Filter_Name : Util.Beans.Objects.Object; Servlet_Name : Util.Beans.Objects.Object; URL_Patterns : Util.Beans.Objects.Vectors.Vector; Param_Name : Util.Beans.Objects.Object; Param_Value : Util.Beans.Objects.Object; Mime_Type : Util.Beans.Objects.Object; Extension : Util.Beans.Objects.Object; Error_Code : Util.Beans.Objects.Object; Location : Util.Beans.Objects.Object; Handler : Servlet_Registry_Access; Context : EL.Contexts.ELContext_Access; end record; type Servlet_Config_Access is access all Servlet_Config; -- Save in the servlet config object the value associated with the given field. -- When the <b>FILTER_MAPPING</b>, <b>SERVLET_MAPPING</b> or <b>CONTEXT_PARAM</b> field -- is reached, insert the new configuration rule in the servlet registry. procedure Set_Member (N : in out Servlet_Config; Field : in Servlet_Fields; Value : in Util.Beans.Objects.Object); -- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>, -- <b>filter-mapping</b> and <b>servlet-mapping</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Handler : in Servlet_Registry_Access; Context : in EL.Contexts.ELContext_Access; package Reader_Config is Config : aliased Servlet_Config; end Reader_Config; private package Servlet_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Servlet_Config, Element_Type_Access => Servlet_Config_Access, Fields => Servlet_Fields, Set_Member => Set_Member); end ASF.Servlets.Mappers;
Allow to have several url-pattern for a filter/servlet mapping
Allow to have several url-pattern for a filter/servlet mapping
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
80d739a09d21ba1b0b44ea33aee10d3c79afd017
src/bbox-api.adb
src/bbox-api.adb
----------------------------------------------------------------------- -- bbox -- Bbox API -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.JSON; with Util.Log.Loggers; with Util.Strings; package body Bbox.API is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API"); -- ------------------------------ -- Set the server IP address. -- ------------------------------ procedure Set_Server (Client : in out Client_Type; Server : in String) is begin Log.Debug ("Using bbox server {0}", Server); Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Internal operation to get the URI based on the operation being called. -- ------------------------------ function Get_URI (Client : in Client_Type; Operation : in String) return String is begin return "http://" & To_String (Client.Server) & "/api/v1/" & Operation; end Get_URI; -- ------------------------------ -- Login to the server Bbox API with the password. -- ------------------------------ procedure Login (Client : in out Client_Type; Password : in String) is procedure Process (Name, Value : in String); URI : constant String := Client.Get_URI ("login"); Response : Util.Http.Clients.Response; procedure Process (Name, Value : in String) is Pos, Last : Natural; begin if Name = "Set-Cookie" then Pos := Util.Strings.Index (Value, '='); if Pos = 0 then return; end if; Last := Util.Strings.Index (Value, ';'); if Last = 0 or else Last < Pos then return; end if; Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1)); end if; end Process; begin Log.Debug ("Login to {0}", URI); Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api"); Client.Http.Post (URI, "password=" & Password, Response); if Response.Get_Status = Util.Http.SC_OK then Response.Iterate_Headers (Process'Access); else Log.Error ("Connection and login to {0} failed", URI); end if; end Login; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the result into the property list. -- ------------------------------ procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); Util.Properties.JSON.Parse_JSON (Result, Response.Get_Body); end Get; end Bbox.API;
----------------------------------------------------------------------- -- bbox -- Bbox API -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.JSON; with Util.Log.Loggers; with Util.Strings; package body Bbox.API is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API"); -- ------------------------------ -- Set the server IP address. -- ------------------------------ procedure Set_Server (Client : in out Client_Type; Server : in String) is begin Log.Debug ("Using bbox server {0}", Server); Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Internal operation to get the URI based on the operation being called. -- ------------------------------ function Get_URI (Client : in Client_Type; Operation : in String) return String is begin return "http://" & To_String (Client.Server) & "/api/v1/" & Operation; end Get_URI; -- ------------------------------ -- Login to the server Bbox API with the password. -- ------------------------------ procedure Login (Client : in out Client_Type; Password : in String) is procedure Process (Name, Value : in String); URI : constant String := Client.Get_URI ("login"); Response : Util.Http.Clients.Response; procedure Process (Name, Value : in String) is Pos, Last : Natural; begin if Name = "Set-Cookie" then Pos := Util.Strings.Index (Value, '='); if Pos = 0 then return; end if; Last := Util.Strings.Index (Value, ';'); if Last = 0 or else Last < Pos then return; end if; Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1)); end if; end Process; begin Log.Debug ("Login to {0}", URI); Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api"); Client.Http.Post (URI, "password=" & Password, Response); if Response.Get_Status = Util.Http.SC_OK then Response.Iterate_Headers (Process'Access); else Log.Error ("Connection and login to {0} failed", URI); end if; end Login; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the result into the property list. -- ------------------------------ procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); Util.Properties.JSON.Parse_JSON (Result, Response.Get_Body); end Get; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the JSON result and return it. -- ------------------------------ function Get (Client : in out Client_Type; Operation : in String) return String is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); return Response.Get_Body; end Get; end Bbox.API;
Implement the Get function
Implement the Get function
Ada
apache-2.0
stcarrez/bbox-ada-api
8f23414bd3052906e0b077bf6ec45bf4f808082c
src/bbox-api.adb
src/bbox-api.adb
----------------------------------------------------------------------- -- bbox -- Bbox API -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.JSON; with Util.Log.Loggers; with Util.Strings; with Util.Properties.Basic; package body Bbox.API is use Ada.Strings.Unbounded; package Int_Property renames Util.Properties.Basic.Integer_Property; package Bool_Property renames Util.Properties.Basic.Boolean_Property; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API"); function Strip_Unecessary_Array (Content : in String) return String; -- ------------------------------ -- Set the server IP address. -- ------------------------------ procedure Set_Server (Client : in out Client_Type; Server : in String) is begin Log.Debug ("Using bbox server {0}", Server); Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Internal operation to get the URI based on the operation being called. -- ------------------------------ function Get_URI (Client : in Client_Type; Operation : in String) return String is begin return "http://" & To_String (Client.Server) & "/api/v1/" & Operation; end Get_URI; -- ------------------------------ -- Login to the server Bbox API with the password. -- ------------------------------ procedure Login (Client : in out Client_Type; Password : in String) is procedure Process (Name, Value : in String); URI : constant String := Client.Get_URI ("login"); Response : Util.Http.Clients.Response; procedure Process (Name, Value : in String) is Pos, Last : Natural; begin if Name = "Set-Cookie" then Pos := Util.Strings.Index (Value, '='); if Pos = 0 then return; end if; Last := Util.Strings.Index (Value, ';'); if Last = 0 or else Last < Pos then return; end if; Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1)); Client.Is_Logged := True; end if; end Process; begin Log.Debug ("Login to {0}", URI); Client.Is_Logged := False; Client.Http.Set_Header ("Cookie", ""); Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api"); Client.Http.Set_Timeout (10.0); Client.Http.Post (URI, "password=" & Password, Response); if Response.Get_Status = Util.Http.SC_OK then Response.Iterate_Headers (Process'Access); else Log.Error ("Connection and login to {0} failed", URI); end if; end Login; -- ------------------------------ -- Strip [] for some Json content. -- We did a mistake when we designed the Bbox API and used '[' ... ']' arrays -- for most of the JSON result. Strip that unecessary array. -- ------------------------------ function Strip_Unecessary_Array (Content : in String) return String is Last : Natural := Content'Last; begin while Last > Content'First and Content (Last) = ASCII.LF loop Last := Last - 1; end loop; if Content (Content'First) = '[' and Content (Last) = ']' then return Content (Content'First + 1 .. Last - 1); else return Content; end if; end Strip_Unecessary_Array; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the result into the property list. -- ------------------------------ procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Set_Timeout (10.0); Client.Http.Get (URI, Response); Util.Properties.JSON.Parse_JSON (Result, Strip_Unecessary_Array (Response.Get_Body)); end Get; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the JSON result and return it. -- ------------------------------ function Get (Client : in out Client_Type; Operation : in String) return String is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Set_Timeout (10.0); Client.Http.Get (URI, Response); return Response.Get_Body; end Get; -- ------------------------------ -- Execute a PUT operation on the Bbox API to change some parameter. -- ------------------------------ procedure Put (Client : in out Client_Type; Operation : in String; Params : in String) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Put {0}", URI); Client.Http.Set_Timeout (10.0); Client.Http.Put (URI, Params, Response); end Put; procedure Refresh_Token (Client : in out Client_Type) is use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Response : Util.Http.Clients.Response; Tokens : Util.Properties.Manager; begin if Length (Client.Token) /= 0 and then Client.Expires > Now then return; end if; Log.Debug ("Get bbox token"); Client.Http.Set_Timeout (10.0); Client.Http.Get (Client.Get_URI ("device/token"), Response); Util.Properties.JSON.Parse_JSON (Tokens, Strip_Unecessary_Array (Response.Get_Body)); Client.Token := To_Unbounded_String (Tokens.Get ("device.token", "")); Client.Expires := Ada.Calendar.Clock + 60.0; end Refresh_Token; -- Execute a POST operation on the Bbox API to change some parameter. procedure Post (Client : in out Client_Type; Operation : in String; Params : in String) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Post {0}", URI); Client.Refresh_Token; Client.Http.Set_Timeout (10.0); Client.Http.Post (URI & "?btoken=" & To_String (Client.Token), Params, Response); end Post; -- Iterate over a JSON array flattened in the properties. procedure Iterate (Props : in Util.Properties.Manager; Name : in String; Process : access procedure (P : in Util.Properties.Manager; Base : in String)) is Count : constant Integer := Int_Property.Get (Props, Name & ".length", 0); begin for I in 0 .. Count loop declare Base : constant String := Name & "." & Util.Strings.Image (I); begin Process (Props, Base); end; end loop; end Iterate; end Bbox.API;
----------------------------------------------------------------------- -- bbox -- Bbox API -- 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.Properties.JSON; with Util.Log.Loggers; with Util.Strings; with Util.Properties.Basic; package body Bbox.API is use Ada.Strings.Unbounded; package Int_Property renames Util.Properties.Basic.Integer_Property; package Bool_Property renames Util.Properties.Basic.Boolean_Property; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API"); function Strip_Unecessary_Array (Content : in String) return String; -- ------------------------------ -- Set the server IP address. -- ------------------------------ procedure Set_Server (Client : in out Client_Type; Server : in String) is begin Log.Debug ("Using bbox server {0}", Server); Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Internal operation to get the URI based on the operation being called. -- ------------------------------ function Get_URI (Client : in Client_Type; Operation : in String) return String is begin return "https://" & To_String (Client.Server) & "/api/v1/" & Operation; end Get_URI; -- ------------------------------ -- Login to the server Bbox API with the password. -- ------------------------------ procedure Login (Client : in out Client_Type; Password : in String) is procedure Process (Name, Value : in String); URI : constant String := Client.Get_URI ("login"); Response : Util.Http.Clients.Response; procedure Process (Name, Value : in String) is Pos, Last : Natural; begin if Name = "Set-Cookie" then Pos := Util.Strings.Index (Value, '='); if Pos = 0 then return; end if; Last := Util.Strings.Index (Value, ';'); if Last = 0 or else Last < Pos then return; end if; Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1)); Client.Is_Logged := True; end if; end Process; begin Log.Debug ("Login to {0}", URI); Client.Is_Logged := False; Client.Http.Set_Header ("Cookie", ""); Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api"); Client.Http.Set_Timeout (10.0); Client.Http.Post (URI, "password=" & Password, Response); if Response.Get_Status = Util.Http.SC_OK then Response.Iterate_Headers (Process'Access); else Log.Error ("Connection and login to {0} failed", URI); end if; end Login; -- ------------------------------ -- Strip [] for some Json content. -- We did a mistake when we designed the Bbox API and used '[' ... ']' arrays -- for most of the JSON result. Strip that unecessary array. -- ------------------------------ function Strip_Unecessary_Array (Content : in String) return String is Last : Natural := Content'Last; begin if Content'Length = 0 then return Content; end if; while Last > Content'First and then Content (Last) = ASCII.LF loop Last := Last - 1; end loop; if Content (Content'First) = '[' and Content (Last) = ']' then return Content (Content'First + 1 .. Last - 1); else return Content; end if; end Strip_Unecessary_Array; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the result into the property list. -- ------------------------------ procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Set_Timeout (10.0); Client.Http.Get (URI, Response); Util.Properties.JSON.Parse_JSON (Result, Strip_Unecessary_Array (Response.Get_Body)); end Get; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the JSON result and return it. -- ------------------------------ function Get (Client : in out Client_Type; Operation : in String) return String is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Set_Timeout (10.0); Client.Http.Get (URI, Response); return Response.Get_Body; end Get; -- ------------------------------ -- Execute a PUT operation on the Bbox API to change some parameter. -- ------------------------------ procedure Put (Client : in out Client_Type; Operation : in String; Params : in String) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Put {0}", URI); Client.Http.Set_Timeout (10.0); Client.Http.Put (URI, Params, Response); end Put; procedure Refresh_Token (Client : in out Client_Type) is use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Response : Util.Http.Clients.Response; Tokens : Util.Properties.Manager; begin if Length (Client.Token) /= 0 and then Client.Expires > Now then return; end if; Log.Debug ("Get bbox token"); Client.Http.Set_Timeout (10.0); Client.Http.Get (Client.Get_URI ("device/token"), Response); Util.Properties.JSON.Parse_JSON (Tokens, Strip_Unecessary_Array (Response.Get_Body)); Client.Token := To_Unbounded_String (Tokens.Get ("device.token", "")); Client.Expires := Ada.Calendar.Clock + 60.0; end Refresh_Token; -- Execute a POST operation on the Bbox API to change some parameter. procedure Post (Client : in out Client_Type; Operation : in String; Params : in String) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Post {0}", URI); Client.Refresh_Token; Client.Http.Set_Timeout (10.0); Client.Http.Post (URI & "?btoken=" & To_String (Client.Token), Params, Response); end Post; -- Iterate over a JSON array flattened in the properties. procedure Iterate (Props : in Util.Properties.Manager; Name : in String; Process : access procedure (P : in Util.Properties.Manager; Base : in String)) is Count : constant Integer := Int_Property.Get (Props, Name & ".length", 0); begin for I in 0 .. Count loop declare Base : constant String := Name & "." & Util.Strings.Image (I); begin Process (Props, Base); end; end loop; end Iterate; end Bbox.API;
Fix to force using HTTPS with latest Bbox firmwares
Fix to force using HTTPS with latest Bbox firmwares
Ada
apache-2.0
stcarrez/bbox-ada-api
d9117fd89d8a59bed584412b483f0b77a6ff0df9
awa/src/awa-blogs-services.adb
awa/src/awa-blogs-services.adb
----------------------------------------------------------------------- -- awa-blogs-services -- Blogs and post management -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Blogs.Models; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with ADO.Sessions; with Ada.Calendar; with Util.Log.Loggers; -- The <b>Blogs.Services</b> package defines the service and operations to -- create, update and delete a post. package body AWA.Blogs.Services is use AWA.Services; use ADO.Sessions; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Blogs.Services"); -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Service; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier) is use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; begin Log.Info ("Creating blog for user"); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => Workspace_Id); Ctx.Start; Blog.Set_Name (Title); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Blog); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Service; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Result : out ADO.Identifier) is use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => Blog_Id); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier; Title : in String; Text : in String) is Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post_Id); Post.Set_Title (Title); Post.Set_Text (Text); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier) is Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post_Id); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Services;
----------------------------------------------------------------------- -- awa-blogs-services -- Blogs and post management -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with AWA.Blogs.Models; with AWA.Services.Contexts; with AWA.Permissions; with AWA.Permissions.Services; with ADO.Sessions; with Ada.Calendar; with Util.Log.Loggers; -- The <b>Blogs.Services</b> package defines the service and operations to -- create, update and delete a post. package body AWA.Blogs.Services is use AWA.Services; use ADO.Sessions; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Blogs.Services"); -- ------------------------------ -- Create a new blog for the user workspace. -- ------------------------------ procedure Create_Blog (Model : in Blog_Service; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; begin Log.Info ("Creating blog for user"); -- Check that the user has the create blog permission on the given workspace. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => Workspace_Id); Ctx.Start; Blog.Set_Name (Title); Blog.Save (DB); -- Add the permission for the user to use the new blog. AWA.Permissions.Services.Add_Permission (Session => DB, User => User, Entity => Blog); Ctx.Commit; Result := Blog.Get_Id; Log.Info ("Blog {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Blog; -- ------------------------------ -- Create a new post associated with the given blog identifier. -- ------------------------------ procedure Create_Post (Model : in Blog_Service; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Result : out ADO.Identifier) is pragma Unreferenced (Model); use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Blog : AWA.Blogs.Models.Blog_Ref; Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Log.Debug ("Creating post for user"); Ctx.Start; -- Get the blog instance. Blog.Load (Session => DB, Id => Blog_Id, Found => Found); if not Found then Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id)); raise Not_Found with "Blog not found"; end if; -- Check that the user has the create post permission on the given blog. AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission, Entity => Blog_Id); -- Build the new post. Post.Set_Title (Title); Post.Set_Text (Text); Post.Set_Create_Date (Ada.Calendar.Clock); Post.Set_Uri (URI); Post.Set_Author (Ctx.Get_User); Post.Save (DB); Ctx.Commit; Result := Post.Get_Id; Log.Info ("Post {0} created for user {1}", ADO.Identifier'Image (Result), ADO.Identifier'Image (User)); end Create_Post; -- ------------------------------ -- Update the post title and text associated with the blog post identified by <b>Post</b>. -- ------------------------------ procedure Update_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier; Title : in String; Text : in String) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the update post permission on the given post. AWA.Permissions.Check (Permission => ACL_Update_Post.Permission, Entity => Post_Id); Post.Set_Title (Title); Post.Set_Text (Text); Post.Save (DB); Ctx.Commit; end Update_Post; -- ------------------------------ -- Delete the post identified by the given identifier. -- ------------------------------ procedure Delete_Post (Model : in Blog_Service; Post_Id : in ADO.Identifier) is pragma Unreferenced (Model); Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Post : AWA.Blogs.Models.Post_Ref; Found : Boolean; begin Ctx.Start; Post.Load (Session => DB, Id => Post_Id, Found => Found); if not Found then Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id)); raise Not_Found; end if; -- Check that the user has the delete post permission on the given post. AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission, Entity => Post_Id); Post.Delete (Session => DB); Ctx.Commit; end Delete_Post; end AWA.Blogs.Services;
Fix compilation of blog module
Fix compilation of blog module
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
af0dd538f9b779f9206cd39dc0e9f84ec837a760
src/security-permissions.adb
src/security-permissions.adb
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; with Security.Controllers; with Security.Controllers.Roles; -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package body Security.Permissions is use Util.Log; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions"); -- A global map to translate a string to a permission index. package Permission_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Permission_Index, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); protected type Global_Index is -- Get the permission index function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index); private Map : Permission_Maps.Map; Next_Index : Permission_Index := Permission_Index'First; end Global_Index; protected body Global_Index is function Get_Permission_Index (Name : in String) return Permission_Index is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then return Permission_Maps.Element (Pos); else raise Invalid_Name with "There is no permission '" & Name & "'"; end if; end Get_Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index is begin return Next_Index; end Get_Last_Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index) is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then Index := Permission_Maps.Element (Pos); else Index := Next_Index; Log.Debug ("Creating permission index {1} for {0}", Name, Permission_Index'Image (Index)); Map.Insert (Name, Index); Next_Index := Next_Index + 1; end if; end Add_Permission; end Global_Index; Permission_Indexes : Global_Index; -- ------------------------------ -- Get the permission index associated with the name. -- ------------------------------ function Get_Permission_Index (Name : in String) return Permission_Index is begin return Permission_Indexes.Get_Permission_Index (Name); end Get_Permission_Index; -- ------------------------------ -- Get the last permission index registered in the global permission map. -- ------------------------------ function Get_Last_Permission_Index return Permission_Index is begin return Permission_Indexes.Get_Last_Permission_Index; end Get_Last_Permission_Index; -- ------------------------------ -- Add the permission name and allocate a unique permission index. -- ------------------------------ procedure Add_Permission (Name : in String; Index : out Permission_Index) is begin Permission_Indexes.Add_Permission (Name, Index); end Add_Permission; -- ------------------------------ -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. -- ------------------------------ function Find_Access_Rule (Manager : in Permission_Manager; URI : in String) return Access_Rule_Ref is Matched : Boolean := False; Result : Access_Rule_Ref; procedure Match (P : in Policy); procedure Match (P : in Policy) is begin if GNAT.Regexp.Match (URI, P.Pattern) then Matched := True; Result := P.Rule; end if; end Match; Last : constant Natural := Manager.Policies.Last_Index; begin for I in 1 .. Last loop Manager.Policies.Query_Element (I, Match'Access); if Matched then return Result; end if; end loop; return Result; end Find_Access_Rule; procedure Add_Permission (Manager : in out Permission_Manager; Name : in String; Permission : in Controller_Access) is Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Returns True if the user has the permission to access the given URI permission. -- ------------------------------ function Has_Permission (Manager : in Permission_Manager; Context : in Security_Context_Access; Permission : in URI_Permission'Class) return Boolean is Name : constant String_Ref := To_String_Ref (Permission.URI); Ref : constant Rules_Ref.Ref := Manager.Cache.Get; Rules : constant Rules_Access := Ref.Value; Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name); Rule : Access_Rule_Ref; begin -- If the rule is not in the cache, search for the access rule that -- matches our URI. Update the cache. This cache update is thread-safe -- as the cache map is never modified: a new cache map is installed. if not Rules_Maps.Has_Element (Pos) then declare New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create; begin Rule := Manager.Find_Access_Rule (Permission.URI); New_Ref.Value.all.Map := Rules.Map; New_Ref.Value.all.Map.Insert (Name, Rule); Manager.Cache.Set (New_Ref); end; else Rule := Rules_Maps.Element (Pos); end if; -- Check if the user has one of the required permission. declare P : constant Access_Rule_Access := Rule.Value; Granted : Boolean; begin if P /= null then for I in P.Permissions'Range loop Context.Has_Permission (P.Permissions (I), Granted); if Granted then return True; end if; end loop; end if; end; return False; end Has_Permission; -- ------------------------------ -- Returns True if the user has the given role permission. -- ------------------------------ function Has_Permission (Manager : in Permission_Manager; User : in Principal'Class; Permission : in Permission_Type) return Boolean is pragma Unreferenced (Manager); begin -- return User.Has_Permission (Permission); return False; end Has_Permission; -- ------------------------------ -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. -- ------------------------------ function Get_Controller (Manager : in Permission_Manager'Class; Index : in Permission_Index) return Controller_Access is begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- ------------------------------ -- Get the role name. -- ------------------------------ function Get_Role_Name (Manager : in Permission_Manager; Role : in Role_Type) return String is use type Ada.Strings.Unbounded.String_Access; begin if Manager.Names (Role) = null then return ""; else return Manager.Names (Role).all; end if; end Get_Role_Name; -- ------------------------------ -- Find the role type associated with the role name identified by <b>Name</b>. -- Raises <b>Invalid_Name</b> if there is no role type. -- ------------------------------ function Find_Role (Manager : in Permission_Manager; Name : in String) return Role_Type is use type Ada.Strings.Unbounded.String_Access; begin Log.Debug ("Searching role {0}", Name); for I in Role_Type'First .. Manager.Next_Role loop exit when Manager.Names (I) = null; if Name = Manager.Names (I).all then return I; end if; end loop; Log.Debug ("Role {0} not found", Name); raise Invalid_Name; end Find_Role; -- ------------------------------ -- Create a role -- ------------------------------ procedure Create_Role (Manager : in out Permission_Manager; Name : in String; Role : out Role_Type) is begin Role := Manager.Next_Role; Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role)); if Manager.Next_Role = Role_Type'Last then Log.Error ("Too many roles allocated. Number of roles is {0}", Role_Type'Image (Role_Type'Last)); else Manager.Next_Role := Manager.Next_Role + 1; end if; Manager.Names (Role) := new String '(Name); end Create_Role; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out Permission_Manager; URI : in String; To : in String) is begin null; end Grant_URI_Permission; -- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b> -- permissions. procedure Grant_File_Permission (Manager : in out Permission_Manager; Path : in String; To : in String) is begin null; end Grant_File_Permission; -- ------------------------------ -- Get or build a permission type for the given name. -- ------------------------------ procedure Add_Role_Type (Manager : in out Permission_Manager; Name : in String; Result : out Role_Type) is begin Result := Manager.Find_Role (Name); exception when Invalid_Name => Manager.Create_Role (Name, Result); end Add_Role_Type; type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object); procedure Process (Policy : in Policy_Config); procedure Set_Member (P : in out Policy_Config; Field : in Policy_Fields; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_ID => P.Id := Util.Beans.Objects.To_Integer (Value); when FIELD_PERMISSION => P.Permissions.Append (Value); when FIELD_URL_PATTERN => P.Patterns.Append (Value); when FIELD_POLICY => Process (P); P.Id := 0; P.Permissions.Clear; P.Patterns.Clear; end case; end Set_Member; procedure Process (Policy : in Policy_Config) is Pol : Security.Permissions.Policy; Count : constant Natural := Natural (Policy.Permissions.Length); Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count)); Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First; Pos : Positive := 1; begin Pol.Rule := Rule; -- Step 1: Initialize the list of permission index in Access_Rule from the permission names. while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); Name : constant String := Util.Beans.Objects.To_String (Perm); begin Rule.Value.all.Permissions (Pos) := Get_Permission_Index (Name); Pos := Pos + 1; exception when Invalid_Name => raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name; end; Util.Beans.Objects.Vectors.Next (Iter); end loop; -- Step 2: Create one policy for each URL pattern Iter := Policy.Patterns.First; while Util.Beans.Objects.Vectors.Has_Element (Iter) loop declare Pattern : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter); begin Pol.Id := Policy.Id; Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern)); Policy.Manager.Policies.Append (Pol); end; Util.Beans.Objects.Vectors.Next (Iter); end loop; end Process; package Policy_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config, Element_Type_Access => Policy_Config_Access, Fields => Policy_Fields, Set_Member => Set_Member); Policy_Mapping : aliased Policy_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the servlet and mapping rules <b>context-param</b>, -- <b>filter-mapping</b> and <b>servlet-mapping</b>. -- ------------------------------ package body Reader_Config is begin Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access); Reader.Add_Mapping ("module", Policy_Mapping'Access); Config.Manager := Manager; Policy_Mapper.Set_Context (Reader, Config'Unchecked_Access); end Reader_Config; -- ------------------------------ -- Read the policy file -- ------------------------------ procedure Read_Policy (Manager : in out Permission_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); package Role_Config is new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); pragma Warnings (Off, Role_Config); begin Log.Info ("Reading policy file {0}", File); Reader.Parse (File); end Read_Policy; -- ------------------------------ -- Initialize the permission manager. -- ------------------------------ overriding procedure Initialize (Manager : in out Permission_Manager) is begin Manager.Cache := new Rules_Ref.Atomic_Ref; Manager.Cache.Set (Rules_Ref.Create); end Initialize; -- ------------------------------ -- Finalize the permission manager. -- ------------------------------ overriding procedure Finalize (Manager : in out Permission_Manager) is use Ada.Strings.Unbounded; use Security.Controllers; procedure Free is new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref, Rules_Ref_Access); procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Security.Controllers.Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin Free (Manager.Cache); for I in Manager.Names'Range loop exit when Manager.Names (I) = null; Ada.Strings.Unbounded.Free (Manager.Names (I)); end loop; if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; package body Permission_ACL is P : Permission_Index; function Permission return Permission_Index is begin return P; end Permission; begin Add_Permission (Name => Name, Index => P); end Permission_ACL; -- ------------------------------ -- EL function to check if the given permission name is granted by the current -- security context. -- ------------------------------ function Has_Permission (Value : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is Name : constant String := Util.Beans.Objects.To_String (Value); begin if Security.Contexts.Has_Permission (Name) then return Util.Beans.Objects.To_Object (True); else return Util.Beans.Objects.To_Object (False); end if; end Has_Permission; -- ------------------------------ -- Register a set of functions in the namespace -- xmlns:fn="http://code.google.com/p/ada-asf/auth" -- Functions: -- hasPermission(NAME) -- Returns True if the permission NAME is granted -- ------------------------------ -- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is -- begin -- Mapper.Set_Function (Name => HAS_PERMISSION_FN, -- Namespace => AUTH_NAMESPACE_URI, -- Func => Has_Permission'Access); -- end Set_Functions; begin Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN); end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with Security.Contexts; with Security.Controllers; with Security.Controllers.Roles; -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package body Security.Permissions is use Util.Log; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions"); -- A global map to translate a string to a permission index. package Permission_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Permission_Index, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); protected type Global_Index is -- Get the permission index function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index); private Map : Permission_Maps.Map; Next_Index : Permission_Index := Permission_Index'First; end Global_Index; protected body Global_Index is function Get_Permission_Index (Name : in String) return Permission_Index is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then return Permission_Maps.Element (Pos); else raise Invalid_Name with "There is no permission '" & Name & "'"; end if; end Get_Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index is begin return Next_Index; end Get_Last_Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index) is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then Index := Permission_Maps.Element (Pos); else Index := Next_Index; Log.Debug ("Creating permission index {1} for {0}", Name, Permission_Index'Image (Index)); Map.Insert (Name, Index); Next_Index := Next_Index + 1; end if; end Add_Permission; end Global_Index; Permission_Indexes : Global_Index; -- ------------------------------ -- Get the permission index associated with the name. -- ------------------------------ function Get_Permission_Index (Name : in String) return Permission_Index is begin return Permission_Indexes.Get_Permission_Index (Name); end Get_Permission_Index; -- ------------------------------ -- Get the last permission index registered in the global permission map. -- ------------------------------ function Get_Last_Permission_Index return Permission_Index is begin return Permission_Indexes.Get_Last_Permission_Index; end Get_Last_Permission_Index; -- ------------------------------ -- Add the permission name and allocate a unique permission index. -- ------------------------------ procedure Add_Permission (Name : in String; Index : out Permission_Index) is begin Permission_Indexes.Add_Permission (Name, Index); end Add_Permission; package body Permission_ACL is P : Permission_Index; function Permission return Permission_Index is begin return P; end Permission; begin Add_Permission (Name => Name, Index => P); end Permission_ACL; end Security.Permissions;
Remove the implementation of old operations which are now in Security.Policy, Security.Policy.Roles and Security.Policy.URLs
Remove the implementation of old operations which are now in Security.Policy, Security.Policy.Roles and Security.Policy.URLs
Ada
apache-2.0
stcarrez/ada-security
5d4824e5d4e891e4836d9d731410da91b6889802
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Interfaces; -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; -- Max number of permissions supported by the implementation. MAX_PERMISSION : constant Natural := 255; type Permission_Index is new Natural range 0 .. MAX_PERMISSION; type Permission_Index_Array is array (Positive range <>) of Permission_Index; NONE : constant Permission_Index := Permission_Index'First; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); type Permission_Index_Set is private; -- Check if the permission index set contains the given permission index. function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean; -- Add the permission index to the set. procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index); -- The empty set of permission indexes. EMPTY_SET : constant Permission_Index_Set; private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8; type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8; EMPTY_SET : constant Permission_Index_Set := (others => 0); end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Interfaces; -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; -- Max number of permissions supported by the implementation. MAX_PERMISSION : constant Natural := 255; type Permission_Index is new Natural range 0 .. MAX_PERMISSION; type Permission_Index_Array is array (Positive range <>) of Permission_Index; NONE : constant Permission_Index := Permission_Index'First; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the permission name given the index. function Get_Name (Index : in Permission_Index) return String; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); type Permission_Index_Set is private; -- Check if the permission index set contains the given permission index. function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean; -- Add the permission index to the set. procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index); -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- The empty set of permission indexes. EMPTY_SET : constant Permission_Index_Set; private INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8; type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8; EMPTY_SET : constant Permission_Index_Set := (others => 0); end Security.Permissions;
Declare the Get_Name function Make the Get_Last_Permission function public
Declare the Get_Name function Make the Get_Last_Permission function public
Ada
apache-2.0
stcarrez/ada-security
b9f53dd3cb806350be3b7786c67646459cbe1cee
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Interfaces; -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; -- Max number of permissions supported by the implementation. MAX_PERMISSION : constant Natural := 256; type Permission_Index is new Natural range 0 .. MAX_PERMISSION; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); type Permission_Index_Set is private; -- Check if the permission index set contains the given permission index. function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean; private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8; type Permission_Index_Set is array (1 .. INDEX_SET_SIZE) of Interfaces.Unsigned_8; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Interfaces; -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; -- Max number of permissions supported by the implementation. MAX_PERMISSION : constant Natural := 256; type Permission_Index is new Natural range 0 .. MAX_PERMISSION; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); type Permission_Index_Set is private; -- Check if the permission index set contains the given permission index. function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean; -- Add the permission index to the set. procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index); private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8; type Permission_Index_Set is array (1 .. INDEX_SET_SIZE) of Interfaces.Unsigned_8; end Security.Permissions;
Declare the Add_Permission procedure to add a permission index to the set
Declare the Add_Permission procedure to add a permission index to the set
Ada
apache-2.0
stcarrez/ada-security
7e8bfc68baee05589dc6c4a95511a9ca8d3c7274
src/util-properties.adb
src/util-properties.adb
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Factories; with Ada.Strings.Unbounded.Text_IO; package body Util.Properties is use Ada.Text_IO; use Ada.Strings.Unbounded.Text_IO; use Interface_P; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False); function Exists (Self : in Manager'Class; Name : in String) return Boolean is begin -- There is not yet an implementation, no property if Self.Impl = null then return False; end if; return Exists (Self.Impl.all, +Name); end Exists; function Exists (Self : in Manager'Class; Name : in Value) return Boolean is begin -- There is not yet an implementation, no property if Self.Impl = null then return False; end if; return Exists (Self.Impl.all, Name); end Exists; function Get (Self : in Manager'Class; Name : in String) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return Get (Self.Impl.all, +Name); end Get; function Get (Self : in Manager'Class; Name : in Value) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & To_String (Name) & "'"; end if; return Get (Self.Impl.all, Name); end Get; function Get (Self : in Manager'Class; Name : in String) return String is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return -Get (Self.Impl.all, +Name); end Get; function Get (Self : in Manager'Class; Name : in Value) return String is begin if Self.Impl = null then raise NO_PROPERTY; end if; return -Get (Self.Impl.all, Name); end Get; function Get (Self : in Manager'Class; Name : in String; Default : in String) return String is Prop_Name : constant Value := +Name; begin if Exists (Self, Prop_Name) then return Get (Self, Prop_Name); else return Default; end if; end Get; procedure Check_And_Create_Impl (Self : in out Manager) is begin if Self.Impl = null then Util.Properties.Factories.Initialize (Self); elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then declare Old : Interface_P.Manager_Access := Self.Impl; Is_Zero : Boolean; begin Self.Impl := Create_Copy (Self.Impl.all); Util.Concurrent.Counters.Increment (Self.Impl.Count); Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero); if Is_Zero then Delete (Old.all, Old); end if; end; end if; end Check_And_Create_Impl; procedure Insert (Self : in out Manager'Class; Name : in String; Item : in String) is begin Check_And_Create_Impl (Self); Insert (Self.Impl.all, +Name, +Item); end Insert; -- ------------------------------ -- 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) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, +Name, +Item); end Set; -- ------------------------------ -- 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) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, +Name, Item); end Set; -- ------------------------------ -- 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) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, Name, Item); end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in String) is begin if Self.Impl = null then raise NO_PROPERTY; end if; Check_And_Create_Impl (Self); Remove (Self.Impl.all, +Name); end Remove; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in Value) is begin if Self.Impl = null then raise NO_PROPERTY; end if; Check_And_Create_Impl (Self); Remove (Self.Impl.all, Name); end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)) is begin if Self.Impl /= null then Self.Impl.Iterate (Process); end if; end Iterate; -- ------------------------------ -- 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 is begin if Self.Impl = null then declare Empty : Name_Array (1 .. 0); begin return Empty; end; else return Get_Names (Self.Impl.all, Prefix); end if; end Get_Names; procedure Adjust (Object : in out Manager) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Count); end if; end Adjust; procedure Finalize (Object : in out Manager) is Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero); if Is_Zero then Delete (Object.Impl.all, Object.Impl); end if; end if; end Finalize; procedure Set_Property_Implementation (Self : in out Manager; Impl : in Interface_P.Manager_Access) is begin if Self.Impl = null then Self.Impl := Impl; -- Self.Impl.Count := 1; end if; end Set_Property_Implementation; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is pragma Unreferenced (Strip); Line : Unbounded_String; Pos : Natural; Len : Natural; begin while not End_Of_File (File) loop Line := Get_Line (File); Len := Length (Line); if Len /= 0 and then Element (Line, 1) /= '#' then Pos := Index (Line, "="); if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1); Value := Tail (Line, Len - Pos); return; elsif Pos > 0 and Prefix'Length = 0 then Name := Head (Line, Pos - 1); Value := Tail (Line, Len - Pos); return; end if; end if; end loop; Name := Null_Unbounded_String; Value := Null_Unbounded_String; end Load_Property; procedure Load_Properties (Self : in out Manager'Class; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is Name, Value : Unbounded_String; begin loop Load_Property (Name, Value, File, Prefix, Strip); exit when Name = Null_Unbounded_String; Set (Self, Name, Value); end loop; exception when End_Error => return; end Load_Properties; procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False) is F : File_Type; begin Open (F, In_File, Path); Load_Properties (Self, F, Prefix, Strip); Close (F); end Load_Properties; -- ------------------------------ -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- ------------------------------ procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False) is Names : constant Name_Array := From.Get_Names; begin for I in Names'Range loop declare Name : Unbounded_String renames Names (I); begin if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then if Strip and Prefix'Length > 0 then declare S : constant String := Slice (Name, Prefix'Length + 1, Length (Name)); begin Self.Set (+(S), From.Get (Name)); end; else Self.Set (Name, From.Get (Name)); end if; end if; end; end loop; end Copy; end Util.Properties;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2012, 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 Util.Properties.Factories; with Ada.IO_Exceptions; with Ada.Strings.Unbounded.Text_IO; with Interfaces.C.Strings; package body Util.Properties is use Ada.Text_IO; use Ada.Strings.Unbounded.Text_IO; use Interface_P; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False); function Exists (Self : in Manager'Class; Name : in String) return Boolean is begin -- There is not yet an implementation, no property if Self.Impl = null then return False; end if; return Exists (Self.Impl.all, +Name); end Exists; function Exists (Self : in Manager'Class; Name : in Value) return Boolean is begin -- There is not yet an implementation, no property if Self.Impl = null then return False; end if; return Exists (Self.Impl.all, Name); end Exists; function Get (Self : in Manager'Class; Name : in String) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return Get (Self.Impl.all, +Name); end Get; function Get (Self : in Manager'Class; Name : in Value) return Value is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & To_String (Name) & "'"; end if; return Get (Self.Impl.all, Name); end Get; function Get (Self : in Manager'Class; Name : in String) return String is begin if Self.Impl = null then raise NO_PROPERTY with "No property: '" & Name & "'"; end if; return -Get (Self.Impl.all, +Name); end Get; function Get (Self : in Manager'Class; Name : in Value) return String is begin if Self.Impl = null then raise NO_PROPERTY; end if; return -Get (Self.Impl.all, Name); end Get; function Get (Self : in Manager'Class; Name : in String; Default : in String) return String is Prop_Name : constant Value := +Name; begin if Exists (Self, Prop_Name) then return Get (Self, Prop_Name); else return Default; end if; end Get; procedure Check_And_Create_Impl (Self : in out Manager) is begin if Self.Impl = null then Util.Properties.Factories.Initialize (Self); elsif Util.Concurrent.Counters.Value (Self.Impl.Count) > 1 then declare Old : Interface_P.Manager_Access := Self.Impl; Is_Zero : Boolean; begin Self.Impl := Create_Copy (Self.Impl.all); Util.Concurrent.Counters.Increment (Self.Impl.Count); Util.Concurrent.Counters.Decrement (Old.Count, Is_Zero); if Is_Zero then Delete (Old.all, Old); end if; end; end if; end Check_And_Create_Impl; procedure Insert (Self : in out Manager'Class; Name : in String; Item : in String) is begin Check_And_Create_Impl (Self); Insert (Self.Impl.all, +Name, +Item); end Insert; -- ------------------------------ -- 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) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, +Name, +Item); end Set; -- ------------------------------ -- 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) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, +Name, Item); end Set; -- ------------------------------ -- 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) is begin Check_And_Create_Impl (Self); Set (Self.Impl.all, Name, Item); end Set; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in String) is begin if Self.Impl = null then raise NO_PROPERTY; end if; Check_And_Create_Impl (Self); Remove (Self.Impl.all, +Name); end Remove; -- ------------------------------ -- Remove the property given its name. -- ------------------------------ procedure Remove (Self : in out Manager'Class; Name : in Value) is begin if Self.Impl = null then raise NO_PROPERTY; end if; Check_And_Create_Impl (Self); Remove (Self.Impl.all, Name); end Remove; -- ------------------------------ -- Iterate over the properties and execute the given procedure passing the -- property name and its value. -- ------------------------------ procedure Iterate (Self : in Manager'Class; Process : access procedure (Name, Item : Value)) is begin if Self.Impl /= null then Self.Impl.Iterate (Process); end if; end Iterate; -- ------------------------------ -- 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 is begin if Self.Impl = null then declare Empty : Name_Array (1 .. 0); begin return Empty; end; else return Get_Names (Self.Impl.all, Prefix); end if; end Get_Names; procedure Adjust (Object : in out Manager) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Count); end if; end Adjust; procedure Finalize (Object : in out Manager) is Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Count, Is_Zero); if Is_Zero then Delete (Object.Impl.all, Object.Impl); end if; end if; end Finalize; procedure Set_Property_Implementation (Self : in out Manager; Impl : in Interface_P.Manager_Access) is begin if Self.Impl = null then Self.Impl := Impl; -- Self.Impl.Count := 1; end if; end Set_Property_Implementation; procedure Load_Property (Name : out Unbounded_String; Value : out Unbounded_String; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is pragma Unreferenced (Strip); Line : Unbounded_String; Pos : Natural; Len : Natural; begin while not End_Of_File (File) loop Line := Get_Line (File); Len := Length (Line); if Len /= 0 and then Element (Line, 1) /= '#' then Pos := Index (Line, "="); if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1); Value := Tail (Line, Len - Pos); return; elsif Pos > 0 and Prefix'Length = 0 then Name := Head (Line, Pos - 1); Value := Tail (Line, Len - Pos); return; end if; end if; end loop; Name := Null_Unbounded_String; Value := Null_Unbounded_String; end Load_Property; procedure Load_Properties (Self : in out Manager'Class; File : in File_Type; Prefix : in String := ""; Strip : in Boolean := False) is Name, Value : Unbounded_String; begin loop Load_Property (Name, Value, File, Prefix, Strip); exit when Name = Null_Unbounded_String; Set (Self, Name, Value); end loop; exception when End_Error => return; end Load_Properties; procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False) is F : File_Type; begin Open (F, In_File, Path); Load_Properties (Self, F, Prefix, Strip); Close (F); end Load_Properties; -- ------------------------------ -- Save the properties in the given file path. -- ------------------------------ procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := "") is procedure Save_Property (Name, Item : in Value); Tmp : constant String := Path & ".tmp"; F : File_Type; procedure Save_Property (Name, Item : in Value) is begin Put (F, Name); Put (F, "="); Put (F, Item); New_Line (F); end Save_Property; -- Rename a file (the Ada.Directories.Rename does not allow to use the Unix atomic file rename!) function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr; Newpath : in Interfaces.C.Strings.chars_ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); Old_Path : Interfaces.C.Strings.chars_ptr; New_Path : Interfaces.C.Strings.chars_ptr; Result : Integer; begin Create (File => F, Name => Tmp); Self.Iterate (Save_Property'Access); Close (File => F); -- Do a system atomic rename of old file in the new file. -- Ada.Directories.Rename does not allow this. Old_Path := Interfaces.C.Strings.New_String (Tmp); New_Path := Interfaces.C.Strings.New_String (Path); Result := Sys_Rename (Old_Path, New_Path); Interfaces.C.Strings.Free (Old_Path); Interfaces.C.Strings.Free (New_Path); if Result /= 0 then raise Ada.IO_Exceptions.Use_Error with "Cannot rename file"; end if; end Save_Properties; -- ------------------------------ -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- ------------------------------ procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False) is Names : constant Name_Array := From.Get_Names; begin for I in Names'Range loop declare Name : Unbounded_String renames Names (I); begin if Prefix'Length = 0 or else Index (Name, Prefix) = 1 then if Strip and Prefix'Length > 0 then declare S : constant String := Slice (Name, Prefix'Length + 1, Length (Name)); begin Self.Set (+(S), From.Get (Name)); end; else Self.Set (Name, From.Get (Name)); end if; end if; end; end loop; end Copy; end Util.Properties;
Implement the Save_Properties procedure to save the properties (use an atomic rename to make sure we don't loose the file in case of problems)
Implement the Save_Properties procedure to save the properties (use an atomic rename to make sure we don't loose the file in case of problems)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9100c4ed87b44b49f6b50e2b481b93806029bf59
src/util-serialize-tools.adb
src/util-serialize-tools.adb
----------------------------------------------------------------------- -- util-serialize-tools -- Tools to Serialize objects in various formats -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.IO.JSON; with Util.Serialize.Mappers.Record_Mapper; package body Util.Serialize.Tools is type Object_Field is (FIELD_NAME, FIELD_VALUE); type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class; type Object_Mapper_Context is record Map : Object_Map_Access; Name : Util.Beans.Objects.Object; end record; type Object_Mapper_Context_Access is access all Object_Mapper_Context; procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_VALUE => Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value); Into.Name := Util.Beans.Objects.Null_Object; end case; end Set_Member; package Object_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context, Element_Type_Access => Object_Mapper_Context_Access, Fields => Object_Field, Set_Member => Set_Member); Object_Mapping : aliased Object_Mapper.Mapper; procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream; Map : in Util.Beans.Objects.Maps.Map) is use type Ada.Containers.Count_Type; procedure Write (Name : in String; Value : in Util.Beans.Objects.Object) is begin Output.Start_Entity (Name => ""); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_Attribute (Name => "value", Value => Value); Output.End_Entity (Name => ""); end Write; begin if Map.Length > 0 then declare Iter : Util.Beans.Objects.Maps.Cursor := Map.First; begin Output.Start_Array (Name => "params", Length => Map.Length); while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access); Util.Beans.Objects.Maps.Next (Iter); end loop; Output.End_Array; end; end if; end To_JSON; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into an XML stream. -- Returns the JSON string that contains a serialization of the object maps. -- ----------------------- function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is use type Ada.Containers.Count_Type; begin if Map.Length = 0 then return ""; end if; declare Output : Util.Serialize.IO.JSON.Output_Stream; begin Output.Initialize (Size => 10000); Output.Start_Document; To_JSON (Output, Map); Output.End_Document; return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Output)); end; end To_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- which their values. -- Returns the object map that was restored. -- ----------------------- function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is Result : aliased Util.Beans.Objects.Maps.Map; Parser : Util.Serialize.IO.JSON.Parser; Context : aliased Object_Mapper_Context; begin Context.Map := Result'Unchecked_Access; Parser.Add_Mapping ("params", Object_Mapping'Access); Object_Mapper.Set_Context (Parser, Context'Unchecked_Access); Parser.Parse (Content); return Result; end From_JSON; begin Object_Mapping.Add_Mapping ("param/@name", FIELD_NAME); Object_Mapping.Add_Mapping ("param", FIELD_VALUE); end Util.Serialize.Tools;
----------------------------------------------------------------------- -- util-serialize-tools -- Tools to Serialize objects in various formats -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Util.Streams.Texts; with Util.Streams.Buffered; with Util.Serialize.IO.JSON; with Util.Serialize.Mappers.Record_Mapper; package body Util.Serialize.Tools is type Object_Field is (FIELD_NAME, FIELD_VALUE); type Object_Map_Access is access all Util.Beans.Objects.Maps.Map'Class; type Object_Mapper_Context is record Map : Object_Map_Access; Name : Util.Beans.Objects.Object; end record; type Object_Mapper_Context_Access is access all Object_Mapper_Context; procedure Set_Member (Into : in out Object_Mapper_Context; Field : in Object_Field; Value : in Util.Beans.Objects.Object) is begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_VALUE => Into.Map.Include (Util.Beans.Objects.To_String (Into.Name), Value); Into.Name := Util.Beans.Objects.Null_Object; end case; end Set_Member; package Object_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Object_Mapper_Context, Element_Type_Access => Object_Mapper_Context_Access, Fields => Object_Field, Set_Member => Set_Member); Object_Mapping : aliased Object_Mapper.Mapper; procedure To_JSON (Output : in out Util.Serialize.IO.JSON.Output_Stream; Map : in Util.Beans.Objects.Maps.Map) is use type Ada.Containers.Count_Type; procedure Write (Name : in String; Value : in Util.Beans.Objects.Object) is begin Output.Start_Entity (Name => ""); Output.Write_Attribute (Name => "name", Value => Util.Beans.Objects.To_Object (Name)); Output.Write_Attribute (Name => "value", Value => Value); Output.End_Entity (Name => ""); end Write; begin if Map.Length > 0 then declare Iter : Util.Beans.Objects.Maps.Cursor := Map.First; begin Output.Start_Array (Name => "params", Length => Map.Length); while Util.Beans.Objects.Maps.Has_Element (Iter) loop Util.Beans.Objects.Maps.Query_Element (Iter, Write'Access); Util.Beans.Objects.Maps.Next (Iter); end loop; Output.End_Array; end; end if; end To_JSON; -- ----------------------- -- Serialize the objects defined in the object map <b>Map</b> into an XML stream. -- Returns the JSON string that contains a serialization of the object maps. -- ----------------------- function To_JSON (Map : in Util.Beans.Objects.Maps.Map) return String is use type Ada.Containers.Count_Type; begin if Map.Length = 0 then return ""; end if; declare Output : Util.Serialize.IO.JSON.Output_Stream; begin Output.Initialize (Size => 10000); Output.Start_Document; To_JSON (Output, Map); Output.End_Document; return Util.Streams.Texts.To_String (Util.Streams.Buffered.Buffered_Stream (Output)); end; end To_JSON; -- ----------------------- -- Deserializes the JSON content passed in <b>Content</b> and restore the object map -- which their values. -- Returns the object map that was restored. -- ----------------------- function From_JSON (Content : in String) return Util.Beans.Objects.Maps.Map is Result : aliased Util.Beans.Objects.Maps.Map; Parser : Util.Serialize.IO.JSON.Parser; Context : aliased Object_Mapper_Context; begin if Content'Length > 0 then Context.Map := Result'Unchecked_Access; Parser.Add_Mapping ("/params", Object_Mapping'Access); Object_Mapper.Set_Context (Parser, Context'Unchecked_Access); Parser.Parse_String (Content); end if; return Result; end From_JSON; begin Object_Mapping.Add_Mapping ("name", FIELD_NAME); Object_Mapping.Add_Mapping ("value", FIELD_VALUE); end Util.Serialize.Tools;
Fix JSON deserialization into an object map
Fix JSON deserialization into an object map
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
feaa9eb84a5b5b72ba4d92fd8b74d39bff8c3d34
src/gen-utils-gnat.adb
src/gen-utils-gnat.adb
----------------------------------------------------------------------- -- gen-utils-gnat -- GNAT utilities -- 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 Csets; with Snames; with Namet; with Prj.Pars; with Prj.Tree; with Prj.Env; with Prj.Util; with Makeutl; with Output; package body Gen.Utils.GNAT is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Utils.GNAT"); Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref; Main_Project : Prj.Project_Id; -- ------------------------------ -- Initialize the GNAT project runtime for reading the GNAT project tree. -- Configure it according to the dynamo configuration properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is Project_Dirs : constant String := Config.Get ("generator.gnat.projects.dir", DEFAULT_GNAT_PROJECT_DIR); begin Log.Info ("Initializing GNAT runtime to read projects from: {0}", Project_Dirs); Project_Node_Tree := new Prj.Tree.Project_Node_Tree_Data; Prj.Tree.Initialize (Project_Node_Tree); Output.Set_Standard_Error; Csets.Initialize; Snames.Initialize; Prj.Initialize (Makeutl.Project_Tree); Prj.Env.Add_Directories (Project_Node_Tree.Project_Path, Project_Dirs); end Initialize; -- ------------------------------ -- Read the GNAT project file identified by <b>Project_File_Name</b> and get -- in <b>Project_List</b> an ordered list of absolute project paths used by -- the root project. -- ------------------------------ procedure Read_GNAT_Project_List (Project_File_Name : in String; Project_List : out Project_Info_Vectors.Vector) is procedure Recursive_Add (Proj : in Prj.Project_Id; Dummy : in out Boolean); function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String; -- Get the variable value represented by the name <b>Name</b>. -- ??? There are probably other efficient ways to get this but I couldn't find them. function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String is use type Prj.Variable_Id; Current : Prj.Variable_Id; The_Variable : Prj.Variable; In_Tree : constant Prj.Project_Tree_Ref := Makeutl.Project_Tree; begin Current := Proj.Decl.Variables; while Current /= Prj.No_Variable loop The_Variable := In_Tree.Variable_Elements.Table (Current); if Namet.Get_Name_String (The_Variable.Name) = Name then return Prj.Util.Value_Of (The_Variable.Value, ""); end if; Current := The_Variable.Next; end loop; return ""; end Get_Variable_Value; -- ------------------------------ -- Add the full path of the GNAT project in the project list. -- ------------------------------ procedure Recursive_Add (Proj : in Prj.Project_Id; Dummy : in out Boolean) is pragma Unreferenced (Dummy); Path : constant String := Namet.Get_Name_String (Proj.Path.Name); Name : constant String := Get_Variable_Value (Proj, "name"); Project : Project_Info; begin Log.Info ("Using GNAT project: {0}", Path); Project.Path := To_Unbounded_String (Path); Project.Name := To_Unbounded_String (Name); Project_List.Append (Project); end Recursive_Add; procedure For_All_Projects is new Prj.For_Every_Project_Imported (Boolean, Recursive_Add); use type Prj.Project_Id; begin Log.Info ("Reading GNAT project {0}", Project_File_Name); -- Parse the GNAT project files and build the tree. Prj.Pars.Parse (Project => Main_Project, In_Tree => Makeutl.Project_Tree, Project_File_Name => Project_File_Name, Flags => Prj.Gnatmake_Flags, In_Node_Tree => Project_Node_Tree); if Main_Project /= Prj.No_Project then declare Dummy : Boolean := False; begin -- Scan the tree to get the list of projects (in dependency order). For_All_Projects (Main_Project, Dummy, Imported_First => True); end; end if; end Read_GNAT_Project_List; end Gen.Utils.GNAT;
----------------------------------------------------------------------- -- gen-utils-gnat -- GNAT utilities -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Gen.Configs; with Csets; with Snames; with Namet; with Prj.Pars; with Prj.Tree; with Prj.Env; with Prj.Util; with Makeutl; with Output; package body Gen.Utils.GNAT is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Utils.GNAT"); Project_Node_Tree : Prj.Tree.Project_Node_Tree_Ref; Main_Project : Prj.Project_Id; -- ------------------------------ -- Initialize the GNAT project runtime for reading the GNAT project tree. -- Configure it according to the dynamo configuration properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is Project_Dirs : constant String := Config.Get (Gen.Configs.GEN_GNAT_PROJECT_DIRS, DEFAULT_GNAT_PROJECT_DIR); begin Log.Info ("Initializing GNAT runtime to read projects from: {0}", Project_Dirs); Project_Node_Tree := new Prj.Tree.Project_Node_Tree_Data; Prj.Tree.Initialize (Project_Node_Tree); Output.Set_Standard_Error; Csets.Initialize; Snames.Initialize; Prj.Initialize (Makeutl.Project_Tree); Prj.Env.Add_Directories (Project_Node_Tree.Project_Path, Project_Dirs); end Initialize; -- ------------------------------ -- Read the GNAT project file identified by <b>Project_File_Name</b> and get -- in <b>Project_List</b> an ordered list of absolute project paths used by -- the root project. -- ------------------------------ procedure Read_GNAT_Project_List (Project_File_Name : in String; Project_List : out Project_Info_Vectors.Vector) is procedure Recursive_Add (Proj : in Prj.Project_Id; Dummy : in out Boolean); function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String; -- Get the variable value represented by the name <b>Name</b>. -- ??? There are probably other efficient ways to get this but I couldn't find them. function Get_Variable_Value (Proj : in Prj.Project_Id; Name : in String) return String is use type Prj.Variable_Id; Current : Prj.Variable_Id; The_Variable : Prj.Variable; In_Tree : constant Prj.Project_Tree_Ref := Makeutl.Project_Tree; begin Current := Proj.Decl.Variables; while Current /= Prj.No_Variable loop The_Variable := In_Tree.Variable_Elements.Table (Current); if Namet.Get_Name_String (The_Variable.Name) = Name then return Prj.Util.Value_Of (The_Variable.Value, ""); end if; Current := The_Variable.Next; end loop; return ""; end Get_Variable_Value; -- ------------------------------ -- Add the full path of the GNAT project in the project list. -- ------------------------------ procedure Recursive_Add (Proj : in Prj.Project_Id; Dummy : in out Boolean) is pragma Unreferenced (Dummy); Path : constant String := Namet.Get_Name_String (Proj.Path.Name); Name : constant String := Get_Variable_Value (Proj, "name"); Project : Project_Info; begin Log.Info ("Using GNAT project: {0}", Path); Project.Path := To_Unbounded_String (Path); Project.Name := To_Unbounded_String (Name); Project_List.Append (Project); end Recursive_Add; procedure For_All_Projects is new Prj.For_Every_Project_Imported (Boolean, Recursive_Add); use type Prj.Project_Id; begin Log.Info ("Reading GNAT project {0}", Project_File_Name); -- Parse the GNAT project files and build the tree. Prj.Pars.Parse (Project => Main_Project, In_Tree => Makeutl.Project_Tree, Project_File_Name => Project_File_Name, Flags => Prj.Gnatmake_Flags, In_Node_Tree => Project_Node_Tree); if Main_Project /= Prj.No_Project then declare Dummy : Boolean := False; begin -- Scan the tree to get the list of projects (in dependency order). For_All_Projects (Main_Project, Dummy, Imported_First => True); end; end if; end Read_GNAT_Project_List; end Gen.Utils.GNAT;
Use the configuration variable
Use the configuration variable
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
92cc2ecec9b741f5b914ac252cb8da6922bc9661
tests/natools-smaz_tests.adb
tests/natools-smaz_tests.adb
------------------------------------------------------------------------------ -- Copyright (c) 2015-2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Streams; with Ada.Strings.Unbounded; with Natools.S_Expressions; with Natools.Smaz_256; with Natools.Smaz_64; with Natools.Smaz_Generic; with Natools.Smaz_Original; with Natools.Smaz_Test_Base_64_Hash; package body Natools.Smaz_Tests is generic with package Smaz is new Natools.Smaz_Generic (<>); with function Image (S : Ada.Streams.Stream_Element_Array) return String; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array); function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String; function Direct_Image (S : Ada.Streams.Stream_Element_Array) return String renames Natools.S_Expressions.To_String; function To_SEA (S : String) return Ada.Streams.Stream_Element_Array renames Natools.S_Expressions.To_Atom; ----------------------- -- Test Dictionaries -- ----------------------- LF : constant Character := Ada.Characters.Latin_1.LF; Dict_64 : constant Natools.Smaz_64.Dictionary := (Last_Code => 59, Values_Last => 119, Variable_Length_Verbatim => False, Max_Word_Length => 6, Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53, 56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98, 101, 102, 103, 105, 111, 112, 114, 115, 118), Values => " ee stainruos l dt enescm pépd de lere ld" & "e" & LF & "on cqumede mentes aiquen teerou r sque , is m q" & "ueà v'tiweblogfanj." & LF & LF & "ch", Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in S'Range loop Append (Result, Ada.Streams.Stream_Element'Image (S (I))); end loop; return To_String (Result); end Decimal_Image; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; begin declare First_OK : Boolean := False; begin declare Buffer : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Decompressed); begin First_OK := True; if Buffer /= Compressed then Test.Fail ("Bad compression of """ & Decompressed & '"'); Test.Info ("Found: " & Image (Buffer)); Test.Info ("Expected:" & Image (Compressed)); declare Round : constant String := Smaz.Decompress (Dict, Buffer); begin if Round /= Decompressed then Test.Info ("Roundtrip failed, got: """ & Round & '"'); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During compression of """ & Decompressed & '"'); end if; Test.Report_Exception (Error, NT.Fail); end; declare First_OK : Boolean := False; begin declare Buffer : constant String := Smaz.Decompress (Dict, Compressed); begin First_OK := True; if Buffer /= Decompressed then Test.Fail ("Bad decompression of " & Image (Compressed)); Test.Info ("Found: """ & Buffer & '"'); Test.Info ("Expected:""" & Decompressed & '"'); declare Round : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Buffer); begin if Round /= Compressed then Test.Info ("Roundtrip failed, got: " & Image (Round)); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During decompression of " & Image (Compressed)); end if; Test.Report_Exception (Error, NT.Fail); end; end Generic_Roundtrip_Test; procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_256, Decimal_Image); procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_64, Direct_Image); ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Report.Section ("Base 256"); All_Tests_256 (Report); Report.End_Section; Report.Section ("Base 64"); All_Tests_64 (Report); Report.End_Section; end All_Tests; ------------------------------ -- Test Suite for Each Base -- ------------------------------ procedure All_Tests_256 (Report : in out NT.Reporter'Class) is begin Test_Validity_256 (Report); Sample_Strings_256 (Report); end All_Tests_256; procedure All_Tests_64 (Report : in out NT.Reporter'Class) is begin Test_Validity_64 (Report); Sample_Strings_64 (Report); end All_Tests_64; ------------------------------- -- Individual Base-256 Tests -- ------------------------------- procedure Sample_Strings_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Smaz_Original.Dictionary, "This is a small string", (254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "foobar", (220, 6, 90, 79)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "the end", (1, 171, 61)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "not-a-g00d-Exampl333", (132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109, 112, 108, 51, 51, 51)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Smaz is a simple compression library", (254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", (254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "this is an example of what works very well with smaz", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", (255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48, 48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ": : : :", (255, 6, 58, 32, 58, 32, 58, 32, 58)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_256; procedure Test_Validity_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_256.Is_Valid (Smaz_Original.Dictionary) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_256; ------------------------------ -- Individual Base-64 Tests -- ------------------------------ procedure Sample_Strings_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Dict_64, "Simple Test", To_SEA ("+TBGSVYA+UBQE")); -- <S>imp* <T>*t Roundtrip_Test (Test, Dict_64, "SiT", To_SEA ("/ATlGV")); -- <SiT> smaller than <S>i<T> ("+TBG+UB") Roundtrip_Test (Test, Dict_64, "sIMple TEST_WITH_14_B", To_SEA ("D9J1EVYA8UVETR1XXlEVI9VM08lQ")); -- s<IM>p* <TE ST_ WIT H_1 4_B> -- TE 001010_10 1010_0010 00 -- ST_ 110010_10 0010_1010 11_111010 -- WIT 111010_10 1001_0010 00_101010 -- H_1 000100_10 1111_1010 10_001100 -- 4_B 001011_00 1111_1010 01_000010 Roundtrip_Test (Test, Dict_64, "'7B_Verbatim'", To_SEA ("0+3IC9lVlJnYF1S0")); -- '<7B_Verb >a*m' -- 7 111011_00 0100 -- B_V 010000_10 1111_1010 01_101010 -- erb 101001_10 0100_1110 01_000110 -- "erb" could have been encoded separately as "o+iB", which has -- the same length, but the tie is broken in favor of the longer -- verbatim fragment to help with corner cases. exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_64; procedure Test_Validity_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_64.Is_Valid (Dict_64) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_64; end Natools.Smaz_Tests;
------------------------------------------------------------------------------ -- Copyright (c) 2015-2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Characters.Latin_1; with Ada.Streams; with Ada.Strings.Unbounded; with Natools.S_Expressions; with Natools.Smaz_256; with Natools.Smaz_64; with Natools.Smaz_Generic; with Natools.Smaz_Original; with Natools.Smaz_Test_Base_64_Hash; package body Natools.Smaz_Tests is generic with package Smaz is new Natools.Smaz_Generic (<>); with function Image (S : Ada.Streams.Stream_Element_Array) return String; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array); function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String; function Direct_Image (S : Ada.Streams.Stream_Element_Array) return String renames Natools.S_Expressions.To_String; function To_SEA (S : String) return Ada.Streams.Stream_Element_Array renames Natools.S_Expressions.To_Atom; ----------------------- -- Test Dictionaries -- ----------------------- LF : constant Character := Ada.Characters.Latin_1.LF; Dict_64 : constant Natools.Smaz_64.Dictionary := (Last_Code => 59, Values_Last => 119, Variable_Length_Verbatim => False, Max_Word_Length => 6, Offsets => (2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 20, 22, 24, 25, 26, 28, 30, 31, 32, 36, 38, 40, 42, 44, 45, 47, 49, 51, 53, 56, 60, 63, 65, 68, 70, 72, 74, 76, 80, 82, 84, 88, 90, 92, 94, 98, 101, 102, 103, 105, 111, 112, 114, 115, 118), Values => " ee stainruos l dt enescm pépd de lere ld" & "e" & LF & "on cqumede mentes aiquen teerou r sque , is m q" & "ueà v'tiweblogfanj." & LF & LF & "ch", Hash => Natools.Smaz_Test_Base_64_Hash.Hash'Access); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Decimal_Image (S : Ada.Streams.Stream_Element_Array) return String is use Ada.Strings.Unbounded; Result : Unbounded_String; begin for I in S'Range loop Append (Result, Ada.Streams.Stream_Element'Image (S (I))); end loop; return To_String (Result); end Decimal_Image; procedure Generic_Roundtrip_Test (Test : in out NT.Test; Dict : in Smaz.Dictionary; Decompressed : in String; Compressed : in Ada.Streams.Stream_Element_Array) is use type Ada.Streams.Stream_Element_Array; use type Ada.Streams.Stream_Element_Offset; begin declare First_OK : Boolean := False; begin declare Buffer : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Decompressed); begin First_OK := True; if Buffer /= Compressed then Test.Fail ("Bad compression of """ & Decompressed & '"'); Test.Info ("Found: " & Image (Buffer)); Test.Info ("Expected:" & Image (Compressed)); declare Round : constant String := Smaz.Decompress (Dict, Buffer); begin if Round /= Decompressed then Test.Info ("Roundtrip failed, got: """ & Round & '"'); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During compression of """ & Decompressed & '"'); end if; Test.Report_Exception (Error, NT.Fail); end; declare First_OK : Boolean := False; begin declare Buffer : constant String := Smaz.Decompress (Dict, Compressed); begin First_OK := True; if Buffer /= Decompressed then Test.Fail ("Bad decompression of " & Image (Compressed)); Test.Info ("Found: """ & Buffer & '"'); Test.Info ("Expected:""" & Decompressed & '"'); declare Round : constant Ada.Streams.Stream_Element_Array := Smaz.Compress (Dict, Buffer); begin if Round /= Compressed then Test.Info ("Roundtrip failed, got: " & Image (Round)); else Test.Info ("Roundtrip OK"); end if; end; end if; end; exception when Error : others => if not First_OK then Test.Info ("During decompression of " & Image (Compressed)); end if; Test.Report_Exception (Error, NT.Fail); end; end Generic_Roundtrip_Test; procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_256, Decimal_Image); procedure Roundtrip_Test is new Generic_Roundtrip_Test (Natools.Smaz_64, Direct_Image); ------------------------- -- Complete Test Suite -- ------------------------- procedure All_Tests (Report : in out NT.Reporter'Class) is begin Report.Section ("Base 256"); All_Tests_256 (Report); Report.End_Section; Report.Section ("Base 64"); All_Tests_64 (Report); Report.End_Section; end All_Tests; ------------------------------ -- Test Suite for Each Base -- ------------------------------ procedure All_Tests_256 (Report : in out NT.Reporter'Class) is begin Test_Validity_256 (Report); Sample_Strings_256 (Report); end All_Tests_256; procedure All_Tests_64 (Report : in out NT.Reporter'Class) is begin Test_Validity_64 (Report); Sample_Strings_64 (Report); end All_Tests_64; ------------------------------- -- Individual Base-256 Tests -- ------------------------------- procedure Sample_Strings_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Smaz_Original.Dictionary, "This is a small string", (254, 84, 76, 56, 172, 62, 173, 152, 62, 195, 70)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "foobar", (220, 6, 90, 79)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "the end", (1, 171, 61)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "not-a-g00d-Exampl333", (132, 204, 4, 204, 59, 255, 12, 48, 48, 100, 45, 69, 120, 97, 109, 112, 108, 51, 51, 51)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Smaz is a simple compression library", (254, 83, 173, 219, 56, 172, 62, 226, 60, 87, 161, 45, 60, 33, 166, 107, 205, 8, 90, 130, 12, 83)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "Nothing is more difficult, and therefore more precious, " & "than to be able to decide", (254, 78, 223, 102, 99, 116, 45, 42, 11, 129, 44, 44, 131, 38, 22, 3, 148, 63, 210, 68, 11, 45, 42, 11, 60, 33, 28, 144, 164, 36, 203, 143, 96, 92, 25, 90, 87, 82, 165, 215, 237, 2)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "this is an example of what works very well with smaz", (155, 56, 172, 41, 2, 250, 4, 45, 60, 87, 32, 159, 135, 65, 42, 254, 107, 23, 231, 71, 145, 152, 243, 227, 10, 173, 219)); Roundtrip_Test (Test, Smaz_Original.Dictionary, "1000 numbers 2000 will 10 20 30 compress very little", (255, 3, 49, 48, 48, 48, 236, 38, 45, 92, 221, 0, 255, 3, 50, 48, 48, 48, 243, 152, 0, 255, 7, 49, 48, 32, 50, 48, 32, 51, 48, 161, 45, 60, 33, 166, 0, 231, 71, 151, 3, 3, 87)); Roundtrip_Test (Test, Smaz_Original.Dictionary, ": : : :", (255, 6, 58, 32, 58, 32, 58, 32, 58)); exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_256; procedure Test_Validity_256 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_256.Is_Valid (Smaz_Original.Dictionary) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_256; ------------------------------ -- Individual Base-64 Tests -- ------------------------------ procedure Sample_Strings_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Roundtrip on sample strings"); begin Roundtrip_Test (Test, Dict_64, "Simple Test", To_SEA ("+TBGSVYA+UBQE")); -- <S>imp* <T>*t Roundtrip_Test (Test, Dict_64, "SiT", To_SEA ("/ATlGV")); -- <SiT> smaller than <S>i<T> ("+TBG+UB") Roundtrip_Test (Test, Dict_64, "sIMple TEST_WITH_14_B", To_SEA ("D9J1EVYA8UVETR1XXlEVI9VM08lQ")); -- s<IM>p* <TE ST_ WIT H_1 4_B> -- TE 001010_10 1010_0010 00 -- ST_ 110010_10 0010_1010 11_111010 -- WIT 111010_10 1001_0010 00_101010 -- H_1 000100_10 1111_1010 10_001100 -- 4_B 001011_00 1111_1010 01_000010 Roundtrip_Test (Test, Dict_64, "'7B_Verbatim'", To_SEA ("0+3IC9lVlJnYF1S0")); -- '<7B_Verb >a*m' -- 7 111011_00 0100 -- B_V 010000_10 1111_1010 01_101010 -- erb 101001_10 0100_1110 01_000110 -- "erb" could have been encoded separately as "o+iB", which has -- the same length, but the tie is broken in favor of the longer -- verbatim fragment to help with corner cases. Roundtrip_Test (Test, Dict_64, "'49 bytes of data to show a verbatim count issue'", To_SEA ("090kTgIWenLK3NFEFAEKs/Ao92dAFAzo+iBF1SepHOvDJB0")); -- '<49 by >tsof_ata_to_< how>_a_ve<b>atm_ontisue' -- e_ d s r i cu _s -- 49 001011_00 1001_1100 10 -- by 000001_00 0100_0110 10_011110 -- how 000101_10 1111_0110 11_101110 --- b 010001_10 0000 exception when Error : others => Test.Report_Exception (Error); end Sample_Strings_64; procedure Test_Validity_64 (Report : in out NT.Reporter'Class) is Test : NT.Test := Report.Item ("Test dictionary validity"); begin if not Natools.Smaz_64.Is_Valid (Dict_64) then Test.Fail; end if; exception when Error : others => Test.Report_Exception (Error); end Test_Validity_64; end Natools.Smaz_Tests;
add a check to show a bug in long verbatim size computation
smaz_tests: add a check to show a bug in long verbatim size computation
Ada
isc
faelys/natools
956ccb01aa324d9ac8f45eac91d2ced189518ae9
src/port_specification-makefile.adb
src/port_specification-makefile.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Text_IO; with Ada.Characters.Latin_1; package body Port_Specification.Makefile is package TIO renames Ada.Text_IO; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- generator -------------------------------------------------------------------------------------------- procedure generator (specs : Portspecs; variant : String; opsys : supported_opsys; arch_standard : supported_arch; osrelease : String; osmajor : String; osversion : String; option_string : String; output_file : String ) is procedure send (data : String; use_put : Boolean := False); procedure send (varname, value : String); procedure send (varname : String; value : HT.Text); procedure send (varname : String; crate : string_crate.Vector); procedure send (varname : String; crate : list_crate.Map); procedure send (varname : String; value : Boolean; dummy : Boolean); procedure send (varname : String; value, default : Integer); procedure print_item (position : string_crate.Cursor); procedure dump_list (position : list_crate.Cursor); procedure dump_distfiles (position : string_crate.Cursor); write_to_file : constant Boolean := (output_file /= ""); makefile_handle : TIO.File_Type; varname_prefix : HT.Text; procedure send (data : String; use_put : Boolean := False) is begin if write_to_file then if use_put then TIO.Put (makefile_handle, data); else TIO.Put_Line (makefile_handle, data); end if; else if use_put then TIO.Put (data); else TIO.Put_Line (data); end if; end if; end send; procedure send (varname, value : String) is begin send (varname & LAT.Equals_Sign & value); end send; procedure send (varname : String; value : HT.Text) is begin if not HT.IsBlank (value) then send (varname & LAT.Equals_Sign & HT.USS (value)); end if; end send; procedure send (varname : String; value : Boolean; dummy : Boolean) is begin if value then send (varname & LAT.Equals_Sign & "yes"); end if; end send; procedure send (varname : String; value, default : Integer) is begin if value /= default then send (varname & LAT.Equals_Sign & HT.int2str (value)); end if; end send; procedure send (varname : String; crate : string_crate.Vector) is begin if crate.Is_Empty then return; end if; if varname = "DISTFILE" then varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_distfiles'Access); else send (varname & "=", True); crate.Iterate (Process => print_item'Access); send (""); end if; end send; procedure send (varname : String; crate : list_crate.Map) is begin varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_list'Access); end send; procedure dump_list (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & "_" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""); end dump_list; procedure print_item (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); begin if index > 1 then send (" ", True); end if; send (HT.USS (string_crate.Element (position)), True); end print_item; procedure dump_distfiles (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); NDX : String := HT.USS (varname_prefix) & "_" & HT.int2str (index) & LAT.Equals_Sign; begin send (NDX & HT.USS (string_crate.Element (position))); end dump_distfiles; begin if not specs.variant_exists (variant) then TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!"); return; end if; if write_to_file then TIO.Create (File => makefile_handle, Mode => TIO.Out_File, Name => output_file); end if; -- TODO: Check these to see if they are actually used. -- The pkg manifests did use many of these, but they will be generated by ravenadm send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF); send ("NAMEBASE", HT.USS (specs.namebase)); send ("VERSION", HT.USS (specs.version)); send ("REVISION", specs.revision, 0); send ("EPOCH", specs.epoch, 0); send ("KEYWORDS", specs.keywords); send ("VARIANT", variant); send ("DL_SITES", specs.dl_sites); send ("DISTFILE", specs.distfiles); send ("DIST_SUBDIR", specs.dist_subdir); send ("DISTNAME", specs.distname); send ("NO_BUILD", specs.skip_build, True); send ("SINGLE_JOB", specs.single_job, True); send ("DESTDIR_VIA_ENV", specs.destdir_env, True); send ("BUILD_WRKSRC", specs.build_wrksrc); send ("MAKEFILE", specs.makefile); send ("MAKE_ENV", specs.make_env); send ("MAKE_ARGS", specs.make_args); send ("CFLAGS", specs.cflags); -- TODO: This probably is not correct ultimately. retrhink. send (".include " & LAT.Quotation & "${.CURDIR:H}/share/mk/raven.mk"); if write_to_file then TIO.Close (makefile_handle); end if; exception when others => if TIO.Is_Open (makefile_handle) then TIO.Close (makefile_handle); end if; end generator; end Port_Specification.Makefile;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Text_IO; with Ada.Characters.Latin_1; package body Port_Specification.Makefile is package TIO renames Ada.Text_IO; package LAT renames Ada.Characters.Latin_1; -------------------------------------------------------------------------------------------- -- generator -------------------------------------------------------------------------------------------- procedure generator (specs : Portspecs; variant : String; opsys : supported_opsys; arch_standard : supported_arch; osrelease : String; osmajor : String; osversion : String; option_string : String; output_file : String ) is procedure send (data : String; use_put : Boolean := False); procedure send (varname, value : String); procedure send (varname : String; value : HT.Text); procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1); procedure send (varname : String; crate : list_crate.Map); procedure send (varname : String; value : Boolean; dummy : Boolean); procedure send (varname : String; value, default : Integer); procedure print_item (position : string_crate.Cursor); procedure dump_list (position : list_crate.Cursor); procedure dump_distfiles (position : string_crate.Cursor); procedure dump_ext_zip (position : string_crate.Cursor); procedure dump_ext_7z (position : string_crate.Cursor); procedure dump_ext_lha (position : string_crate.Cursor); -- procedure dump_ext_HT (position : string_crate.Cursor); write_to_file : constant Boolean := (output_file /= ""); makefile_handle : TIO.File_Type; varname_prefix : HT.Text; procedure send (data : String; use_put : Boolean := False) is begin if write_to_file then if use_put then TIO.Put (makefile_handle, data); else TIO.Put_Line (makefile_handle, data); end if; else if use_put then TIO.Put (data); else TIO.Put_Line (data); end if; end if; end send; procedure send (varname, value : String) is begin send (varname & LAT.Equals_Sign & value); end send; procedure send (varname : String; value : HT.Text) is begin if not HT.IsBlank (value) then send (varname & LAT.Equals_Sign & HT.USS (value)); end if; end send; procedure send (varname : String; value : Boolean; dummy : Boolean) is begin if value then send (varname & LAT.Equals_Sign & "yes"); end if; end send; procedure send (varname : String; value, default : Integer) is begin if value /= default then send (varname & LAT.Equals_Sign & HT.int2str (value)); end if; end send; procedure send (varname : String; crate : string_crate.Vector; flavor : Positive := 1) is begin if crate.Is_Empty then return; end if; case flavor is when 1 => send (varname & "=", True); crate.Iterate (Process => print_item'Access); send (""); when 2 => varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_distfiles'Access); when 3 => crate.Iterate (Process => dump_ext_zip'Access); when 4 => crate.Iterate (Process => dump_ext_7z'Access); when 5 => crate.Iterate (Process => dump_ext_lha'Access); when others => null; end case; end send; procedure send (varname : String; crate : list_crate.Map) is begin varname_prefix := HT.SUS (varname); crate.Iterate (Process => dump_list'Access); end send; procedure dump_list (position : list_crate.Cursor) is NDX : String := HT.USS (varname_prefix) & "_" & HT.USS (list_crate.Element (position).group) & LAT.Equals_Sign; begin send (NDX, True); list_crate.Element (position).list.Iterate (Process => print_item'Access); send (""); end dump_list; procedure print_item (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); begin if index > 1 then send (" ", True); end if; send (HT.USS (string_crate.Element (position)), True); end print_item; procedure dump_distfiles (position : string_crate.Cursor) is index : Natural := string_crate.To_Index (position); NDX : String := HT.USS (varname_prefix) & "_" & HT.int2str (index) & LAT.Equals_Sign; begin send (NDX & HT.USS (string_crate.Element (position))); end dump_distfiles; procedure dump_ext_zip (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=/usr/bin/unzip -qo"); send ("EXTRACT_TAIL_" & N & "=-d ${EXTRACT_WRKDIR_" & N & "}"); end dump_ext_zip; procedure dump_ext_7z (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=7z x -bd -y -o${EXTRACT_WRKDIR_" & N & "} >/dev/null"); send ("EXTRACT_TAIL_" & N & "=# empty"); end dump_ext_7z; procedure dump_ext_lha (position : string_crate.Cursor) is N : String := HT.USS (string_crate.Element (position)); begin send ("EXTRACT_HEAD_" & N & "=lha xfpw=${EXTRACT_WRKDIR_" & N & "}"); send ("EXTRACT_TAIL_" & N & "=# empty"); end dump_ext_lha; -- procedure dump_ext_HT (position : string_crate.Cursor) -- is -- index : Natural := string_crate.To_Index (position); -- begin -- end dump_ext_HT; begin if not specs.variant_exists (variant) then TIO.Put_Line ("Error : Variant '" & variant & "' does not exist!"); return; end if; if write_to_file then TIO.Create (File => makefile_handle, Mode => TIO.Out_File, Name => output_file); end if; -- TODO: Check these to see if they are actually used. -- The pkg manifests did use many of these, but they will be generated by ravenadm send ("# Makefile has been autogenerated by ravenadm tool" & LAT.LF); send ("NAMEBASE", HT.USS (specs.namebase)); send ("VERSION", HT.USS (specs.version)); send ("REVISION", specs.revision, 0); send ("EPOCH", specs.epoch, 0); send ("KEYWORDS", specs.keywords); -- probably remove send ("VARIANT", variant); send ("DL_SITES", specs.dl_sites); send ("DISTFILE", specs.distfiles, 2); send ("DIST_SUBDIR", specs.dist_subdir); send ("DISTNAME", specs.distname); send ("DF_INDEX", specs.df_index); send ("EXTRACT_ONLY", specs.extract_only); send ("ZIP-EXTRACT", specs.extract_zip, 3); send ("7Z-EXTRACT", specs.extract_7z, 4); send ("LHA-EXTRACT", specs.extract_lha, 5); send ("NO_BUILD", specs.skip_build, True); send ("SINGLE_JOB", specs.single_job, True); send ("DESTDIR_VIA_ENV", specs.destdir_env, True); send ("BUILD_WRKSRC", specs.build_wrksrc); send ("MAKEFILE", specs.makefile); send ("MAKE_ENV", specs.make_env); send ("MAKE_ARGS", specs.make_args); send ("CFLAGS", specs.cflags); -- TODO: This is not correct, placeholder. rethink. send (".include " & LAT.Quotation & "/usr/raven/share/mk/raven.mk" & LAT.Quotation); if write_to_file then TIO.Close (makefile_handle); end if; exception when others => if TIO.Is_Open (makefile_handle) then TIO.Close (makefile_handle); end if; end generator; end Port_Specification.Makefile;
Save progress, several EXTRACT_WITH_* directives implemented
Save progress, several EXTRACT_WITH_* directives implemented
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
90470695eb31049c6af0b3c7445d74f1a17858f1
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; 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; begin if Context = null then Log.Debug ("There is no security context, permission denied"); raise NO_PERMISSION; end if; Context.Add_Context ("entity_id", ADO.Identifier'Image (Entity)); if not (Security.Contexts.Has_Permission (Permission)) then Log.Debug ("Permission is refused"); raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Get from the security context <b>Context</b> an identifier stored under the -- name <b>Name</b>. Returns NO_IDENTIFIER if the security context does not define -- such name or the value is not a valid identifier. -- ------------------------------ function Get_Context (Context : in Security.Contexts.Security_Context'Class; Name : in String) return ADO.Identifier is begin declare Value : constant String := Context.Get_Context (Name); begin return ADO.Identifier'Value (Value); exception when Security.Contexts.Invalid_Context => return ADO.NO_IDENTIFIER; when Constraint_Error => return ADO.NO_IDENTIFIER; end; end Get_Context; 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); 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;
Implement the Entity_Policy
Implement the Entity_Policy
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
140363971ce12397197e6b8478bf9752295ae576
src/sys/os-unix/util-systems-os.ads
src/sys/os-unix/util-systems-os.ads
----------------------------------------------------------------------- -- util-systems-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.LF; use Util.Systems.Constants; 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; subtype File_Type is Util.Systems.Types.File_Type; -- 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 use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! 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 with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "read"; function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "write"; -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer) with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "exit"; -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execvp"; -- Execute a process with the given arguments. function Sys_Execve (File : in Ptr; Args : in Ptr_Array; Envp : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execve"; -- 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 with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "waitpid"; -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "pipe"; -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "dup2"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "open"; -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fcntl"; function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "kill"; function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.STAT_NAME; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.FSTAT_NAME; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "lseek"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "ftruncate"; function Sys_Truncate (Path : in Ptr; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "truncate"; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fchmod"; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chmod"; -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chdir"; -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "rename"; -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "__get_errno"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "strerror"; end Util.Systems.Os;
----------------------------------------------------------------------- -- util-systems-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 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 System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; -- The line ending separator. Line_Separator : constant String := "" & ASCII.LF; use Util.Systems.Constants; 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; subtype File_Type is Util.Systems.Types.File_Type; -- 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 use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! 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 with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "read"; function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "write"; -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer) with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "exit"; -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fork"; -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execvp"; -- Execute a process with the given arguments. function Sys_Execve (File : in Ptr; Args : in Ptr_Array; Envp : in Ptr_Array) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "execve"; -- 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 with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "waitpid"; -- Get the current process identification. function Sys_Getpid return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "getpid"; -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "pipe"; -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "dup2"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "close"; -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "open"; -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fcntl"; function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "kill"; function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.STAT_NAME; function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer with Import => True, Convention => C, Link_Name => Util.Systems.Types.FSTAT_NAME; function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "lseek"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "ftruncate"; function Sys_Truncate (Path : in Ptr; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "truncate"; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "fchmod"; -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chmod"; -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "chdir"; -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "rename"; -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "__get_errno"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => C, Link_Name => SYMBOL_PREFIX & "strerror"; end Util.Systems.Os;
Add Sys_Getpid definition
Add Sys_Getpid definition
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
246e756cc35b828a697d5ef4d2b75f3bd4853081
src/gen-artifacts.ads
src/gen-artifacts.ads
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- 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 DOM.Core; with Gen.Model; with Gen.Model.Packages; with Gen.Model.Projects; -- The <b>Gen.Artifacts</b> package represents the methods and process to prepare, -- control and realize the code generation. package Gen.Artifacts is type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE); type Generator is limited interface; -- Report an error and set the exit status accordingly procedure Error (Handler : in out Generator; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is abstract; -- Get the result directory path. function Get_Result_Directory (Handler : in Generator) return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in String := "") return String is abstract; -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (Handler : in out Generator; Name : in String; Mode : in Iteration_Mode) is abstract; -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (Handler : in Generator; Process : not null access procedure (Dir : in String)) is abstract; -- ------------------------------ -- Model Definition -- ------------------------------ type Artifact is abstract new Ada.Finalization.Limited_Controlled with private; -- 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); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is null; -- After the generation, perform a finalization step for the generation process. procedure Finish (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- Check whether this artifact has been initialized. function Is_Initialized (Handler : in Artifact) return Boolean; private type Artifact is abstract new Ada.Finalization.Limited_Controlled with record Initialized : Boolean := False; end record; end Gen.Artifacts;
----------------------------------------------------------------------- -- gen-artifacts -- Artifacts for Code Generator -- 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 DOM.Core; with Gen.Model; with Gen.Model.Packages; with Gen.Model.Projects; -- The <b>Gen.Artifacts</b> package represents the methods and process to prepare, -- control and realize the code generation. package Gen.Artifacts is type Iteration_Mode is (ITERATION_PACKAGE, ITERATION_TABLE); type Generator is limited interface; -- Report an error and set the exit status accordingly procedure Error (Handler : in out Generator; Message : in String; Arg1 : in String := ""; Arg2 : in String := "") is abstract; -- Get the config directory path. function Get_Config_Directory (Handler : in Generator) return String is abstract; -- Get the result directory path. function Get_Result_Directory (Handler : in Generator) return String is abstract; -- Get the configuration parameter. function Get_Parameter (Handler : in Generator; Name : in String; Default : in String := "") return String is abstract; -- Tell the generator to activate the generation of the given template name. -- The name is a property name that must be defined in generator.properties to -- indicate the template file. Several artifacts can trigger the generation -- of a given template. The template is generated only once. procedure Add_Generation (Handler : in out Generator; Name : in String; Mode : in Iteration_Mode) is abstract; -- Scan the dynamo directories and execute the <b>Process</b> procedure with the -- directory path. procedure Scan_Directories (Handler : in Generator; Process : not null access procedure (Dir : in String)) is abstract; -- ------------------------------ -- Model Definition -- ------------------------------ type Artifact is abstract new Ada.Finalization.Limited_Controlled with private; -- 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); -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class) is null; -- After the generation, perform a finalization step for the generation process. procedure Finish (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Project : in out Gen.Model.Projects.Project_Definition'Class; Context : in out Generator'Class) is null; -- Check whether this artifact has been initialized. function Is_Initialized (Handler : in Artifact) return Boolean; private type Artifact is abstract new Ada.Finalization.Limited_Controlled with record Initialized : Boolean := False; end record; end Gen.Artifacts;
Add the Get_Config_Directory function to the artifact interface
Add the Get_Config_Directory function to the artifact interface
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
4e5cd8c690b58afe14070818a4655e20429b3301
samples/beans/messages.adb
samples/beans/messages.adb
----------------------------------------------------------------------- -- messages - A simple memory-based forum -- 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.Events.Faces.Actions; package body Messages is use Ada.Strings.Unbounded; Database : aliased Forum; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Message_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "text" then return Util.Beans.Objects.To_Object (From.Text); elsif Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "id" then return Util.Beans.Objects.To_Object (Integer (From.Id)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Message_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "text" then From.Text := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" then From.Id := Message_Id (Util.Beans.Objects.To_Integer (Value)); end if; end Set_Value; -- ------------------------------ -- Post the message. -- ------------------------------ procedure Post (From : in out Message_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin if Length (From.Text) > 200 then Ada.Strings.Unbounded.Replace_Slice (From.Text, 200, Length (From.Text), "..."); end if; Database.Post (From); Outcome := To_Unbounded_String ("posted"); end Post; package Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Message_Bean, Method => Post, Name => "post"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Post_Binding.Proxy'Unchecked_Access, Post_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Message_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a message bean instance. -- ------------------------------ function Create_Message_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Message_Bean_Access := new Message_Bean; begin return Result.all'Access; end Create_Message_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Forum_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.Get_Count)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Forum_Bean) return Natural is pragma Unreferenced (From); begin return Database.Get_Message_Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Forum_Bean; Index : in Natural) is begin From.Pos := Message_Id (Index); From.Msg := Database.Get_Message (From.Pos); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Forum_Bean) return Util.Beans.Objects.Object is begin return From.Current; end Get_Row; -- ------------------------------ -- Create the list of messages. -- ------------------------------ function Create_Message_List return Util.Beans.Basic.Readonly_Bean_Access is F : constant Forum_Bean_Access := new Forum_Bean; begin F.Current := Util.Beans.Objects.To_Object (F.Msg'Access, Util.Beans.Objects.STATIC); return F.all'Access; end Create_Message_List; protected body Forum is -- ------------------------------ -- Post the message in the forum. -- ------------------------------ procedure Post (Message : in Message_Bean) is use type Ada.Containers.Count_Type; begin if Messages.Length > 100 then Messages.Delete (Message_Id'First); end if; Messages.Append (Message); end Post; -- ------------------------------ -- Delete the message identified by <b>Id</b>. -- ------------------------------ procedure Delete (Id : in Message_Id) is begin Messages.Delete (Id); end Delete; -- ------------------------------ -- Get the message identified by <b>Id</b>. -- ------------------------------ function Get_Message (Id : in Message_Id) return Message_Bean is begin return Messages.Element (Id); end Get_Message; -- ------------------------------ -- Get the number of messages in the forum. -- ------------------------------ function Get_Message_Count return Natural is begin return Natural (Messages.Length); end Get_Message_Count; end Forum; end Messages;
----------------------------------------------------------------------- -- messages - A simple memory-based forum -- Copyright (C) 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Util.Beans.Objects.Time; with ASF.Events.Faces.Actions; package body Messages is use Ada.Strings.Unbounded; Database : aliased Forum; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ function Get_Value (From : in Message_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "text" then return Util.Beans.Objects.To_Object (From.Text); elsif Name = "email" then return Util.Beans.Objects.To_Object (From.Email); elsif Name = "id" then return Util.Beans.Objects.To_Object (Integer (From.Id)); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ procedure Set_Value (From : in out Message_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "text" then From.Text := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "email" then From.Email := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" then From.Id := Message_Id (Util.Beans.Objects.To_Integer (Value)); end if; end Set_Value; -- ------------------------------ -- Post the message. -- ------------------------------ procedure Post (From : in out Message_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin if Length (From.Text) > 200 then Ada.Strings.Unbounded.Replace_Slice (From.Text, 200, Length (From.Text), "..."); end if; Database.Post (From); Outcome := To_Unbounded_String ("posted"); end Post; package Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Message_Bean, Method => Post, Name => "post"); Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array := (Post_Binding.Proxy'Unchecked_Access, Post_Binding.Proxy'Unchecked_Access); -- ------------------------------ -- This bean provides some methods that can be used in a Method_Expression -- ------------------------------ overriding function Get_Method_Bindings (From : in Message_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Binding_Array'Access; end Get_Method_Bindings; -- ------------------------------ -- Create a message bean instance. -- ------------------------------ function Create_Message_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Message_Bean_Access := new Message_Bean; begin return Result.all'Access; end Create_Message_Bean; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Forum_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (Integer (From.Get_Count)); elsif Name = "today" then return Util.Beans.Objects.Time.To_Object (Ada.Calendar.Clock); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Get the number of elements in the list. -- ------------------------------ overriding function Get_Count (From : in Forum_Bean) return Natural is pragma Unreferenced (From); begin return Database.Get_Message_Count; end Get_Count; -- ------------------------------ -- Set the current row index. Valid row indexes start at 1. -- ------------------------------ overriding procedure Set_Row_Index (From : in out Forum_Bean; Index : in Natural) is begin From.Pos := Message_Id (Index); From.Msg := Database.Get_Message (From.Pos); end Set_Row_Index; -- ------------------------------ -- Get the element at the current row index. -- ------------------------------ overriding function Get_Row (From : in Forum_Bean) return Util.Beans.Objects.Object is begin return From.Current; end Get_Row; -- ------------------------------ -- Create the list of messages. -- ------------------------------ function Create_Message_List return Util.Beans.Basic.Readonly_Bean_Access is F : constant Forum_Bean_Access := new Forum_Bean; begin F.Current := Util.Beans.Objects.To_Object (F.Msg'Access, Util.Beans.Objects.STATIC); return F.all'Access; end Create_Message_List; protected body Forum is -- ------------------------------ -- Post the message in the forum. -- ------------------------------ procedure Post (Message : in Message_Bean) is use type Ada.Containers.Count_Type; begin if Messages.Length > 100 then Messages.Delete (Message_Id'First); end if; Messages.Append (Message); end Post; -- ------------------------------ -- Delete the message identified by <b>Id</b>. -- ------------------------------ procedure Delete (Id : in Message_Id) is begin Messages.Delete (Id); end Delete; -- ------------------------------ -- Get the message identified by <b>Id</b>. -- ------------------------------ function Get_Message (Id : in Message_Id) return Message_Bean is begin return Messages.Element (Id); end Get_Message; -- ------------------------------ -- Get the number of messages in the forum. -- ------------------------------ function Get_Message_Count return Natural is begin return Natural (Messages.Length); end Get_Message_Count; end Forum; end Messages;
Add a bean value 'today' to retrieve the current date and time in an XHTML view
Add a bean value 'today' to retrieve the current date and time in an XHTML view
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
f06f72eedb7b8b8272b5108be59ec969766c14b6
src/gen-model-tables.ads
src/gen-model-tables.ads
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
----------------------------------------------------------------------- -- gen-model-tables -- Database table model representation -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Util.Beans.Objects; with Gen.Model.List; with Gen.Model.Packages; with Gen.Model.Mappings; with Gen.Model.Operations; package Gen.Model.Tables is use Ada.Strings.Unbounded; type Table_Definition; type Table_Definition_Access is access all Table_Definition'Class; -- ------------------------------ -- Column Definition -- ------------------------------ type Column_Definition is new Definition with record Number : Natural := 0; Table : Table_Definition_Access; -- Whether the column must not be null in the database Not_Null : Boolean := False; -- Whether the column must be unique Unique : Boolean := False; -- The column type name. Type_Name : Unbounded_String; -- The SQL type associated with the column. Sql_Type : Unbounded_String; -- The SQL name associated with the column. Sql_Name : Unbounded_String; -- True if this column is the optimistic locking version column. Is_Version : Boolean := False; -- True if this column is the primary key column. Is_Key : Boolean := False; -- True if the column can be read by the application. Is_Readable : Boolean := True; -- True if the column is included in the insert statement Is_Inserted : Boolean := True; -- True if the column is included in the update statement Is_Updated : Boolean := True; -- True if the Ada mapping must use the foreign key type. Use_Foreign_Key_Type : Boolean := False; -- The class generator to use for this column. Generator : Util.Beans.Objects.Object; end record; type Column_Definition_Access is access all Column_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Column_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Column_Definition); -- Returns true if the column type is a basic type. function Is_Basic_Type (From : Column_Definition) return Boolean; -- Returns the column type. function Get_Type (From : Column_Definition) return String; -- Returns the column type mapping. function Get_Type_Mapping (From : in Column_Definition) return Gen.Model.Mappings.Mapping_Definition_Access; package Column_List is new Gen.Model.List (T => Column_Definition, T_Access => Column_Definition_Access); -- ------------------------------ -- Association Definition -- ------------------------------ type Association_Definition is new Column_Definition with private; type Association_Definition_Access is access all Association_Definition'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Association_Definition; Name : String) return Util.Beans.Objects.Object; package Operation_List is new Gen.Model.List (T => Gen.Model.Operations.Operation_Definition, T_Access => Gen.Model.Operations.Operation_Definition_Access); package Table_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Table_Definition_Access); -- ------------------------------ -- Table Definition -- ------------------------------ type Table_Definition is new Mappings.Mapping_Definition with record Members : aliased Column_List.List_Definition; Members_Bean : Util.Beans.Objects.Object; Operations : aliased Operation_List.List_Definition; Operations_Bean : Util.Beans.Objects.Object; Parent : Table_Definition_Access; Package_Def : Gen.Model.Packages.Package_Definition_Access; Type_Name : Unbounded_String; Pkg_Name : Unbounded_String; Table_Name : Unbounded_String; Version_Column : Column_Definition_Access; Id_Column : Column_Definition_Access; Has_Associations : Boolean := False; -- The list of tables that this table depends on. Dependencies : Table_Vectors.Vector; -- Controls whether the <tt>Vector</tt> type and the <tt>List</tt> procedure must -- be generated. Has_List : Boolean := True; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Table_Definition; Name : String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Table_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Table_Definition); -- Collect the dependencies to other tables. procedure Collect_Dependencies (O : in out Table_Definition); type Dependency_Type is (NONE, FORWARD, BACKWARD); -- CIRCULAR is not yet managed. -- Get the dependency between the two tables. -- Returns NONE if both table don't depend on each other. -- Returns FORWARD if the <tt>Left</tt> table depends on <tt>Right</tt>. -- Returns BACKWARD if the <tt>Right</tt> table depends on <tt>Left</tt>. function Depends_On (Left, Right : in Table_Definition_Access) return Dependency_Type; -- Create a table with the given name. function Create_Table (Name : in Unbounded_String) return Table_Definition_Access; -- Create a table column with the given name and add it to the table. procedure Add_Column (Table : in out Table_Definition; Name : in Unbounded_String; Column : out Column_Definition_Access); -- Create a table association with the given name and add it to the table. procedure Add_Association (Table : in out Table_Definition; Name : in Unbounded_String; Assoc : out Association_Definition_Access); -- Set the table name and determines the package name. procedure Set_Table_Name (Table : in out Table_Definition; Name : in String); package Table_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Table_Definition_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Table_Cursor is Table_Map.Cursor; -- Returns true if the table cursor contains a valid table function Has_Element (Position : Table_Cursor) return Boolean renames Table_Map.Has_Element; -- Returns the table definition. function Element (Position : Table_Cursor) return Table_Definition_Access renames Table_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Table_Cursor) renames Table_Map.Next; private type Association_Definition is new Column_Definition with null record; end Gen.Model.Tables;
Add support to manage table dependencies - keep the dependencies for each table, - new operation Depends_On to get the dependency status bewteen two tables
Add support to manage table dependencies - keep the dependencies for each table, - new operation Depends_On to get the dependency status bewteen two tables
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
d205f108283471363391af90a1459f481fe19eff
matp/src/mat-expressions.adb
matp/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Events.Targets.Event_Id_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Update Is_Selected to check for the thread
Update Is_Selected to check for the thread
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0b127f8cb5d26ac0510d604e011507b0ba3d985c
src/util-serialize-mappers-record_mapper.ads
src/util-serialize-mappers-record_mapper.ads
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Record_Mapper -- Mapper for record 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.Beans.Objects; with Util.Serialize.IO; generic type Element_Type (<>) is limited private; type Element_Type_Access is access all Element_Type; type Fields is (<>); -- The <b>Set_Member</b> procedure will be called by the mapper when a mapping associated -- with <b>Field</b> is recognized. The <b>Value</b> holds the value that was extracted -- according to the mapping. The <b>Set_Member</b> procedure should save in the target -- object <b>Into</b> the value. If an error is detected, the procedure can raise the -- <b>Util.Serialize.Mappers.Field_Error</b> exception. The exception message will be -- reported by the IO reader as an error. with procedure Set_Member (Into : in out Element_Type; Field : in Fields; Value : in Util.Beans.Objects.Object); -- Adding a second function/procedure as generic parameter makes the -- Vector_Mapper generic package fail to instantiate a valid package. -- The failure occurs in Vector_Mapper in the 'with package Element_Mapper' instantiation. -- -- with function Get_Member (From : in Element_Type; -- Field : in Fields) return Util.Beans.Objects.Object; package Util.Serialize.Mappers.Record_Mapper is type Get_Member_Access is access function (From : in Element_Type; Field : in Fields) return Util.Beans.Objects.Object; -- Procedure to give access to the <b>Element_Type</b> object from the context. type Process_Object is not null access procedure (Ctx : in out Util.Serialize.Contexts.Context'Class; Attr : in Mapping'Class; Value : in Util.Beans.Objects.Object; Process : not null access procedure (Attr : in Mapping'Class; Item : in out Element_Type; Value : in Util.Beans.Objects.Object)); type Proxy_Object is not null access procedure (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- Set the attribute member described by the <b>Attr</b> mapping -- into the value passed in <b>Element</b>. This operation will call -- the package parameter function of the same name. procedure Set_Member (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. type Element_Data is new Util.Serialize.Contexts.Data with private; type Element_Data_Access is access all Element_Data'Class; -- Get the element object. function Get_Element (Data : in Element_Data) return Element_Type_Access; -- Set the element object. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Element (Data : in out Element_Data; Element : in Element_Type_Access; Release : in Boolean := False); -- Finalize the object when it is removed from the reader context. -- If the <b>Release</b> parameter was set, the target element will be freed. overriding procedure Finalize (Data : in out Element_Data); -- ----------------------- -- Record mapper -- ----------------------- type Mapper is new Util.Serialize.Mappers.Mapper with private; type Mapper_Access is access all Mapper'Class; -- 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); -- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b> -- is matched, the <b>Set_Member</b> procedure will be called with the value and the -- <b>Field</b> identification. procedure Add_Mapping (Into : in out Mapper; Path : in String; Field : in Fields); -- Add a mapping associated with the path and described by a mapper object. -- The <b>Proxy</b> procedure is in charge of giving access to the target -- object used by the <b>Map</b> mapper. procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Util.Serialize.Mappers.Mapper_Access; Proxy : in Proxy_Object); -- Clone the <b>Handler</b> instance and get a copy of that single object. overriding function Clone (Handler : in Mapper) return Util.Serialize.Mappers.Mapper_Access; -- procedure Bind (Into : in out Mapper; Getter : in Get_Member_Access); procedure Bind (Into : in out Mapper; From : in Mapper_Access); function Get_Getter (From : in Mapper) return Get_Member_Access; -- Set the element in the context. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Element : in Element_Type_Access; Release : in Boolean := False); -- Build a default mapping based on the <b>Fields</b> enumeration. -- The enumeration name is used for the mapping name with the optional <b>FIELD_</b> -- prefix stripped. procedure Add_Default_Mapping (Into : in out Mapper); -- 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 Element_Type); -- Write the element on the stream using the mapper description. procedure Write (Handler : in Util.Serialize.Mappers.Mapper'Class; Getter : in Get_Member_Access; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Element_Type); private type Element_Data is new Util.Serialize.Contexts.Data with record Element : Element_Type_Access; Release : Boolean; end record; type Mapper is new Util.Serialize.Mappers.Mapper with record Execute : Proxy_Object := Set_Member'Access; Get_Member : Get_Member_Access; end record; type Attribute_Mapping is new Mapping with record Index : Fields; end record; type Attribute_Mapping_Access is access all Attribute_Mapping'Class; procedure Set_Member (Attr : in Attribute_Mapping; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); type Proxy_Mapper is new Mapper with null record; type Proxy_Mapper_Access is access all Proxy_Mapper'Class; -- Find the mapper associated with the given name. -- Returns null if there is no mapper. overriding function Find_Mapper (Controller : in Proxy_Mapper; Name : in String; Attribute : in Boolean := False) return Util.Serialize.Mappers.Mapper_Access; end Util.Serialize.Mappers.Record_Mapper;
----------------------------------------------------------------------- -- Util.Serialize.Mappers.Record_Mapper -- Mapper for record types -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Serialize.IO; generic type Element_Type (<>) is limited private; type Element_Type_Access is access all Element_Type; type Fields is (<>); -- The <b>Set_Member</b> procedure will be called by the mapper when a mapping associated -- with <b>Field</b> is recognized. The <b>Value</b> holds the value that was extracted -- according to the mapping. The <b>Set_Member</b> procedure should save in the target -- object <b>Into</b> the value. If an error is detected, the procedure can raise the -- <b>Util.Serialize.Mappers.Field_Error</b> exception. The exception message will be -- reported by the IO reader as an error. with procedure Set_Member (Into : in out Element_Type; Field : in Fields; Value : in Util.Beans.Objects.Object); -- Adding a second function/procedure as generic parameter makes the -- Vector_Mapper generic package fail to instantiate a valid package. -- The failure occurs in Vector_Mapper in the 'with package Element_Mapper' instantiation. -- -- with function Get_Member (From : in Element_Type; -- Field : in Fields) return Util.Beans.Objects.Object; package Util.Serialize.Mappers.Record_Mapper is type Get_Member_Access is access function (From : in Element_Type; Field : in Fields) return Util.Beans.Objects.Object; -- Procedure to give access to the <b>Element_Type</b> object from the context. type Process_Object is not null access procedure (Ctx : in out Util.Serialize.Contexts.Context'Class; Attr : in Mapping'Class; Value : in Util.Beans.Objects.Object; Process : not null access procedure (Attr : in Mapping'Class; Item : in out Element_Type; Value : in Util.Beans.Objects.Object)); type Proxy_Object is not null access procedure (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- Set the attribute member described by the <b>Attr</b> mapping -- into the value passed in <b>Element</b>. This operation will call -- the package parameter function of the same name. procedure Set_Member (Attr : in Mapping'Class; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); -- ----------------------- -- Data context -- ----------------------- -- Data context to get access to the target element. type Element_Data is new Util.Serialize.Contexts.Data with private; type Element_Data_Access is access all Element_Data'Class; -- Get the element object. function Get_Element (Data : in Element_Data) return Element_Type_Access; -- Set the element object. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Element (Data : in out Element_Data; Element : in Element_Type_Access; Release : in Boolean := False); -- Finalize the object when it is removed from the reader context. -- If the <b>Release</b> parameter was set, the target element will be freed. overriding procedure Finalize (Data : in out Element_Data); -- ----------------------- -- Record mapper -- ----------------------- type Mapper is new Util.Serialize.Mappers.Mapper with private; type Mapper_Access is access all Mapper'Class; -- 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); -- Add a mapping for setting a member. When the attribute rule defined by <b>Path</b> -- is matched, the <b>Set_Member</b> procedure will be called with the value and the -- <b>Field</b> identification. procedure Add_Mapping (Into : in out Mapper; Path : in String; Field : in Fields); -- Add a mapping associated with the path and described by a mapper object. -- The <b>Proxy</b> procedure is in charge of giving access to the target -- object used by the <b>Map</b> mapper. procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Util.Serialize.Mappers.Mapper_Access; Proxy : in Proxy_Object); -- Clone the <b>Handler</b> instance and get a copy of that single object. overriding function Clone (Handler : in Mapper) return Util.Serialize.Mappers.Mapper_Access; -- procedure Bind (Into : in out Mapper; Getter : in Get_Member_Access); procedure Bind (Into : in out Mapper; From : in Mapper_Access); function Get_Getter (From : in Mapper) return Get_Member_Access; -- Set the element in the context. When <b>Release</b> is set, the element <b>Element</b> -- will be freed when the reader context is deleted (by <b>Finalize</b>). procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class; Element : in Element_Type_Access; Release : in Boolean := False); -- Build a default mapping based on the <b>Fields</b> enumeration. -- The enumeration name is used for the mapping name with the optional <b>FIELD_</b> -- prefix stripped. procedure Add_Default_Mapping (Into : in out Mapper); -- 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 Element_Type); -- Write the element on the stream using the mapper description. procedure Write (Handler : in Util.Serialize.Mappers.Mapper'Class; Getter : in Get_Member_Access; Stream : in out Util.Serialize.IO.Output_Stream'Class; Element : in Element_Type); private type Element_Data is new Util.Serialize.Contexts.Data with record Element : Element_Type_Access; Release : Boolean; end record; type Mapper is new Util.Serialize.Mappers.Mapper with record Execute : Proxy_Object := Set_Member'Access; Get_Member : Get_Member_Access; end record; type Attribute_Mapping is new Mapping with record Index : Fields; end record; type Attribute_Mapping_Access is access all Attribute_Mapping'Class; procedure Set_Member (Attr : in Attribute_Mapping; Element : in out Element_Type; Value : in Util.Beans.Objects.Object); type Proxy_Mapper is new Mapper with null record; type Proxy_Mapper_Access is access all Proxy_Mapper'Class; -- Find the mapper associated with the given name. -- Returns null if there is no mapper. overriding function Find_Mapper (Controller : in Proxy_Mapper; Name : in String; Attribute : in Boolean := False) return Util.Serialize.Mappers.Mapper_Access; end Util.Serialize.Mappers.Record_Mapper;
Fix header
Fix header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6fa9a4882d0b0b59e4058f93f70dbf8d6a0b6d0f
src/gen-commands-page.adb
src/gen-commands-page.adb
----------------------------------------------------------------------- -- gen-commands-page -- Page creation command for dynamo -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with GNAT.Command_Line; with Util.Strings; package body Gen.Commands.Page is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; use Ada.Strings.Unbounded; function Get_Layout return String; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory & "web/"; function Get_Name return String is Name : constant String := Get_Argument; Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is Layout : constant String := Get_Argument; begin if Layout'Length = 0 then return "layout"; end if; if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Info ("Layout file {0} not found.", Layout); return Layout; end Get_Layout; Name : constant String := Get_Name; Layout : constant String := Get_Layout; begin if Name'Length = 0 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); Generator.Set_Global ("pageName", Name); Generator.Set_Global ("layout", Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page"); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Text_IO; use Ada.Directories; Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts"; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Search : Search_Type; Ent : Directory_Entry_Type; begin Put_Line ("add-page: Add a new web page to the application"); Put_Line ("Usage: add-page NAME [LAYOUT]"); New_Line; Put_Line (" The web page is an XHTML file created under the 'web' directory."); Put_Line (" The NAME can contain a directory that will be created if necessary."); Put_Line (" The new web page can be configured to use the given layout."); Put_Line (" The layout file must exist to be used. The default layout is 'layout'."); Put_Line (" You can create a new layout with 'add-layout' command."); Put_Line (" You can also write your layout by adding an XHTML file in the directory:"); Put_Line (" " & Path); if Exists (Path) then New_Line; Put_Line (" Available layouts:"); Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Layout : constant String := Base_Name (Name); begin Put_Line (" " & Layout); end; end loop; end if; New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/<name>.xhtml"); end Help; end Gen.Commands.Page;
----------------------------------------------------------------------- -- gen-commands-page -- Page 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 Util.Strings; package body Gen.Commands.Page is -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use Ada.Strings.Unbounded; function Get_Layout return String; function Get_Name return String; Dir : constant String := Generator.Get_Result_Directory & "web/"; function Get_Name return String is Name : constant String := Args.Get_Argument (1); Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos = 0 then return Name; elsif Name (Pos .. Name'Last) = ".xhtml" then return Name (Name'First .. Pos - 1); elsif Name (Pos .. Name'Last) = ".html" then return Name (Name'First .. Pos - 1); else return Name; end if; end Get_Name; function Get_Layout return String is begin if Args.Get_Count = 1 then return "layout"; end if; declare Layout : constant String := Args.Get_Argument (2); begin if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then return Layout; end if; Generator.Info ("Layout file {0} not found.", Layout); return Layout; end; end Get_Layout; begin if Args.Get_Count = 0 or Args.Get_Count > 2 then Gen.Commands.Usage; return; end if; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Dir); Generator.Set_Global ("pageName", Get_Name); Generator.Set_Global ("layout", Get_Layout); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page"); 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); use Ada.Text_IO; use Ada.Directories; Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts"; Filter : constant Filter_Type := (Ordinary_File => True, others => False); Search : Search_Type; Ent : Directory_Entry_Type; begin Put_Line ("add-page: Add a new web page to the application"); Put_Line ("Usage: add-page NAME [LAYOUT]"); New_Line; Put_Line (" The web page is an XHTML file created under the 'web' directory."); Put_Line (" The NAME can contain a directory that will be created if necessary."); Put_Line (" The new web page can be configured to use the given layout."); Put_Line (" The layout file must exist to be used. The default layout is 'layout'."); Put_Line (" You can create a new layout with 'add-layout' command."); Put_Line (" You can also write your layout by adding an XHTML file in the directory:"); Put_Line (" " & Path); if Exists (Path) then New_Line; Put_Line (" Available layouts:"); Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter); while More_Entries (Search) loop Get_Next_Entry (Search, Ent); declare Name : constant String := Simple_Name (Ent); Layout : constant String := Base_Name (Name); begin Put_Line (" " & Layout); end; end loop; end if; New_Line; Put_Line (" The following files are generated:"); Put_Line (" web/<name>.xhtml"); end Help; end Gen.Commands.Page;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
06094d7135a2367d9dde61ce4fc45270d5c2d1d0
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Views; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; H : Applications.Views.View_Handler; Writer : aliased Contexts.Writer.String.String_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Resolver : aliased Default_ELResolver; Conf : Applications.Config; begin loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin -- if Pos > 0 then -- Variables.Set_Variable (Value (1 .. Pos - 1), -- To_Object (Value (Pos + 1 .. Value'Last))); -- else -- Variables.Set_Variable (Value, To_Object(True)); -- end if; null; end; when others => exit; end case; end loop; Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); declare View_Name : constant String := Get_Argument; begin H.Initialize (Conf); 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/xml", "UTF-8", 8192); Set_Current (Context'Unchecked_Access); H.Restore_View (View_Name, Context, View); H.Render_View (Context, View); Writer.Flush; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Writer.Get_Response)); H.Close; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
----------------------------------------------------------------------- -- render -- XHTML Rendering example -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Exceptions; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Strings.Fixed; with GNAT.Command_Line; with ASF.Applications.Views; with ASF.Components.Core; with ASF.Contexts.Faces; with ASF.Contexts.Writer.String; with EL.Objects; with EL.Contexts; with EL.Contexts.Default; with EL.Variables; with EL.Variables.Default; with ASF.Streams; -- This example reads an XHTML file and renders the result. procedure Render is use GNAT.Command_Line; use Ada.Strings.Fixed; use ASF; use ASF.Contexts.Faces; use EL.Contexts.Default; use EL.Variables; use EL.Variables.Default; use EL.Contexts; use EL.Objects; H : Applications.Views.View_Handler; Writer : aliased Contexts.Writer.String.String_Writer; Context : aliased Faces_Context; View : Components.Core.UIViewRoot; ELContext : aliased EL.Contexts.Default.Default_Context; Variables : aliased Default_Variable_Mapper; Resolver : aliased Default_ELResolver; Conf : Applications.Config; Output : ASF.Streams.Print_Stream; begin loop case Getopt ("D:") is when 'D' => declare Value : constant String := Parameter; Pos : constant Natural := Index (Value, "="); begin -- if Pos > 0 then -- Variables.Set_Variable (Value (1 .. Pos - 1), -- To_Object (Value (Pos + 1 .. Value'Last))); -- else -- Variables.Set_Variable (Value, To_Object(True)); -- end if; null; end; when others => exit; end case; end loop; Conf.Set ("view.ignore_white_spaces", "false"); Conf.Set ("view.escape_unknown_tags", "false"); Conf.Set ("view.ignore_empty_lines", "true"); declare View_Name : constant String := Get_Argument; begin H.Initialize (Conf); 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/xml", "UTF-8", Output); Set_Current (Context'Unchecked_Access); H.Restore_View (View_Name, Context, View); H.Render_View (Context, View); Writer.Flush; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Writer.Get_Response)); H.Close; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & View_Name & "'"); end; end Render;
Fix compilation
Fix compilation
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
49bd04d6a85fdfaf056d4810bbde41730c0e5ebe
samples/render.adb
samples/render.adb
----------------------------------------------------------------------- -- render -- Wiki rendering example -- Copyright (C) 2015, 2016, 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 Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Directories; with GNAT.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Filters.Autolink; with Wiki.Plugins.Templates; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; procedure Render is use GNAT.Command_Line; use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-H] [-d] [-c] [-s style] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -T Render a Textile wiki content"); Ada.Text_IO.Put_Line (" -H Render a HTML wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (True); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; Count : Natural := 0; Html_Mode : Boolean := True; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; begin loop case Getopt ("m M d c g t T H s:") is when 'm' => Syntax := Wiki.SYNTAX_MARKDOWN; when 'M' => Syntax := Wiki.SYNTAX_MEDIA_WIKI; when 'c' => Syntax := Wiki.SYNTAX_CREOLE; when 'd' => Syntax := Wiki.SYNTAX_DOTCLEAR; when 'H' => Syntax := Wiki.SYNTAX_HTML; when 'T' => Syntax := Wiki.SYNTAX_TEXTILE; when 'g' => Syntax := Wiki.SYNTAX_GOOGLE; when 't' => Html_Mode := False; when 's' => Style := To_Unbounded_String (Parameter); when others => exit; end case; end loop; loop declare Name : constant String := GNAT.Command_Line.Get_Argument; Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin if Name = "" then if Count = 0 then Usage; end if; return; end if; Count := Count + 1; Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name)); -- Open the file and parse it (assume UTF-8). Input.Open (Name, "WCEM=8"); Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); end; end loop; exception when Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option."); Usage; end Render;
----------------------------------------------------------------------- -- render -- Wiki rendering example -- 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. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Strings.Unbounded; with Ada.Directories; with Ada.Command_Line; with Wiki.Documents; with Wiki.Parsers; with Wiki.Filters.TOC; with Wiki.Filters.Html; with Wiki.Filters.Autolink; with Wiki.Plugins.Templates; with Wiki.Render.Html; with Wiki.Render.Text; with Wiki.Streams.Text_IO; with Wiki.Streams.Html.Text_IO; procedure Render is use Ada.Strings.Unbounded; procedure Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String); procedure Render_Text (Doc : in out Wiki.Documents.Document); Arg_Count : constant Natural := Ada.Command_Line.Argument_Count; Count : Natural := 0; Html_Mode : Boolean := True; Html_Toc : Boolean := False; Syntax : Wiki.Wiki_Syntax := Wiki.SYNTAX_MARKDOWN; Style : Unbounded_String; Indent : Natural := 3; procedure Usage is begin Ada.Text_IO.Put_Line ("Render a wiki text file into HTML (default) or text"); Ada.Text_IO.Put_Line ("Usage: render [-t] [-m] [-M] [-H] [-d] [-c] [-s style] {wiki-file}"); Ada.Text_IO.Put_Line (" -t Render to text only"); Ada.Text_IO.Put_Line (" -m Render a Markdown wiki content"); Ada.Text_IO.Put_Line (" -M Render a Mediawiki wiki content"); Ada.Text_IO.Put_Line (" -T Render a Textile wiki content"); Ada.Text_IO.Put_Line (" -H Render a HTML wiki content"); Ada.Text_IO.Put_Line (" -d Render a Dotclear wiki content"); Ada.Text_IO.Put_Line (" -g Render a Google wiki content"); Ada.Text_IO.Put_Line (" -c Render a Creole wiki content"); Ada.Text_IO.Put_Line (" -s style Use the CSS style file"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Usage; procedure Render_Html (Doc : in out Wiki.Documents.Document; Style : in Unbounded_String) is Output : aliased Wiki.Streams.Html.Text_IO.Html_Output_Stream; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Output.Set_Indent_Level (Indent); if Length (Style) > 0 then Output.Start_Element ("html"); Output.Start_Element ("head"); Output.Start_Element ("link"); Output.Write_Attribute ("type", "text/css"); Output.Write_Attribute ("rel", "stylesheet"); Output.Write_Attribute ("href", To_String (Style)); Output.End_Element ("link"); Output.End_Element ("head"); Output.Start_Element ("body"); end if; Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Set_Render_TOC (Html_Toc); Renderer.Render (Doc); if Length (Style) > 0 then Output.End_Element ("body"); Output.End_Element ("html"); end if; end Render_Html; procedure Render_Text (Doc : in out Wiki.Documents.Document) is Output : aliased Wiki.Streams.Text_IO.File_Output_Stream; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Output_Stream (Output'Unchecked_Access); Renderer.Render (Doc); end Render_Text; procedure Render_File (Name : in String) is Input : aliased Wiki.Streams.Text_IO.File_Input_Stream; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; Autolink : aliased Wiki.Filters.Autolink.Autolink_Filter; Template : aliased Wiki.Plugins.Templates.File_Template_Plugin; TOC : aliased Wiki.Filters.TOC.TOC_Filter; Doc : Wiki.Documents.Document; Engine : Wiki.Parsers.Parser; begin Count := Count + 1; Template.Set_Template_Path (Ada.Directories.Containing_Directory (Name)); -- Open the file and parse it (assume UTF-8). if Name /= "--" then Input.Open (Name, "WCEM=8"); end if; Engine.Set_Plugin_Factory (Template'Unchecked_Access); Engine.Add_Filter (TOC'Unchecked_Access); Engine.Add_Filter (Autolink'Unchecked_Access); Engine.Add_Filter (Filter'Unchecked_Access); Engine.Set_Syntax (Syntax); Engine.Parse (Input'Unchecked_Access, Doc); -- Render the document in text or HTML. if Html_Mode then Render_Html (Doc, Style); else Render_Text (Doc); end if; exception when Ada.IO_Exceptions.Name_Error => Ada.Text_IO.Put_Line ("Cannot read file '" & Name & "'"); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Render_File; begin for I in 1 .. Arg_Count loop declare Param : constant String := Ada.Command_Line.Argument (I); begin if Param = "-m" then Syntax := Wiki.SYNTAX_MARKDOWN; elsif Param = "-M" then Syntax := Wiki.SYNTAX_MEDIA_WIKI; elsif Param = "-c" then Syntax := Wiki.SYNTAX_CREOLE; elsif Param = "-d" then Syntax := Wiki.SYNTAX_DOTCLEAR; elsif Param = "-H" then Syntax := Wiki.SYNTAX_HTML; elsif Param = "-T" then Syntax := Wiki.SYNTAX_TEXTILE; elsif Param = "-g" then Syntax := Wiki.SYNTAX_GOOGLE; elsif Param = "-t" then Html_Mode := False; elsif Param = "-z" then Html_Toc := True; elsif Param = "-s" then Style := To_Unbounded_String (Param); elsif Param = "--" then Render_File (Param); elsif Param = "-0" then Indent := 0; elsif Param = "-1" then Indent := 1; elsif Param = "-2" then Indent := 2; elsif Param (Param'First) = '-' then Usage; return; else Render_File (Param); end if; end; end loop; if Count = 0 then Usage; end if; end Render;
Update the render example to allow reading the standard input and configure the html indentation level
Update the render example to allow reading the standard input and configure the html indentation level
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
fc1b98cb9b2133a9e6510f2b11f4c134b2e26597
regtests/ado-queries-tests.adb
regtests/ado-queries-tests.adb
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- Copyright (C) 2011 - 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 ADO.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; function Loader (Name : in String) return access constant String; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Find_Query", Test_Find_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query (reload)", Test_Reload_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query", Test_Set_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Limit", Test_Set_Limit'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Get_SQL (raise Query_Error)", Test_Missing_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query_Loader", Test_Query_Loader'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Missing_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/missing-query.xml", Sha1 => ""); package Internal_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/internal-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); package Internal_Query is new ADO.Queries.Loaders.Query (Name => "internal-query", File => Internal_Query_File.File'Access); package Missing_Query_SQLite is new ADO.Queries.Loaders.Query (Name => "missing-query-sqlite", File => Missing_Query_File.File'Access); package Missing_Query_MySQL is new ADO.Queries.Loaders.Query (Name => "missing-query-mysql", File => Missing_Query_File.File'Access); package Missing_Query_Postgresql is new ADO.Queries.Loaders.Query (Name => "missing-query-postgresql", File => Missing_Query_File.File'Access); package Missing_Query is new ADO.Queries.Loaders.Query (Name => "missing-query", File => Missing_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); pragma Warnings (Off, Missing_Query); pragma Warnings (Off, Missing_Query_SQLite); pragma Warnings (Off, Missing_Query_MySQL); pragma Warnings (Off, Missing_Query_Postgresql); pragma Warnings (Off, Internal_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Connections; use type ADO.Configs.Driver_Index; Mysql_Driver : constant Driver_Access := ADO.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Connections.Get_Driver ("sqlite"); Psql_Driver : constant Driver_Access := ADO.Connections.Get_Driver ("postgresql"); Config : ADO.Connections.Configuration; Manager : Query_Manager; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin -- Configure the XML query loader. Config.Set_Connection (Config_URL); ADO.Queries.Loaders.Initialize (Manager, Config); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then Assert_Equals (T, "select 1", SQL, "Invalid query for 'index'"); elsif Psql_Driver /= null and then Manager.Driver = Psql_Driver.Get_Driver_Index then Assert_Equals (T, "select 3", SQL, "Invalid query for 'index'"); else Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end if; end; if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null and then Manager.Driver = Sqlite_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; if Psql_Driver /= null and then Manager.Driver = Psql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 3", SQL, "Invalid query for 'index' (PostgreSQL driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test re-loading queries. -- ------------------------------ procedure Test_Reload_Queries (T : in out Test) is Config : ADO.Connections.Configuration; Manager : Query_Manager; Query : ADO.Queries.Context; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin -- Configure the XML query loader. Config.Set_Connection (Config_URL); ADO.Queries.Loaders.Initialize (Manager, Config); for I in 1 .. 10 loop Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; for J in Manager.Files'Range loop Manager.Files (J).Next_Check := 0; end loop; end loop; end Test_Reload_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is Config : ADO.Connections.Configuration; Manager : Query_Manager; Pos : Query_Index; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin Config.Set_Connection (Config_URL); -- Configure and load the XML queries. for Pass in 1 .. 10 loop Config.Set_Property ("ado.queries.load", (if Pass = 1 then "false" else "true")); ADO.Queries.Loaders.Initialize (Manager, Config); T.Assert (Manager.Queries /= null, "The queries table is allocated"); T.Assert (Manager.Files /= null, "The files table is allocated"); Pos := 1; for Query of Manager.Queries.all loop if Pass = 1 then T.Assert (Query.Is_Null, "Query must not be loaded"); elsif Missing_Query.Query.Query /= Pos and Internal_Query.Query.Query /= Pos then T.Assert (not Query.Is_Null, "Query must have been loaded"); else T.Assert (Query.Is_Null, "Query must not be loaded (not found)"); end if; Pos := Pos + 1; end loop; end loop; end Test_Initialize; -- ------------------------------ -- Test the Set_Query operation. -- ------------------------------ procedure Test_Set_Query (T : in out Test) is Query : ADO.Queries.Context; Manager : Query_Manager; Config : ADO.Connections.Configuration; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin Config.Set_Connection (Config_URL); ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; end Test_Set_Query; -- ------------------------------ -- Test the Set_Limit operation. -- ------------------------------ procedure Test_Set_Limit (T : in out Test) is Query : ADO.Queries.Context; begin Query.Set_Query ("index"); Query.Set_Limit (0, 10); Assert_Equals (T, 0, Query.Get_First_Row_Index, "Invalid first row index"); Assert_Equals (T, 10, Query.Get_Last_Row_Index, "Invalid last row index"); end Test_Set_Limit; -- ------------------------------ -- Test the Find_Query operation. -- ------------------------------ procedure Test_Find_Query (T : in out Test) is Q : Query_Definition_Access; begin Q := ADO.Queries.Loaders.Find_Query ("this query does not exist"); T.Assert (Q = null, "Find_Query should return null for unkown query"); end Test_Find_Query; -- ------------------------------ -- Test the missing query. -- ------------------------------ procedure Test_Missing_Query (T : in out Test) is Query : ADO.Queries.Context; Manager : Query_Manager; Config : ADO.Connections.Configuration; Count : Natural := 0; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin Config.Set_Connection (Config_URL); ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("missing-query"); begin Assert_Equals (T, "?", Query.Get_SQL (Manager)); T.Fail ("No ADO.Queries.Query_Error exception was raised"); exception when ADO.Queries.Query_Error => null; end; begin Query.Set_Query ("missing-query-sqlite"); Assert_Equals (T, "select count(*) from user", Query.Get_SQL (Manager)); exception when ADO.Queries.Query_Error => Count := Count + 1; end; begin Query.Set_Query ("missing-query-mysql"); Assert_Equals (T, "select count(*) from user", Query.Get_SQL (Manager)); exception when ADO.Queries.Query_Error => Count := Count + 1; end; begin Query.Set_Query ("missing-query-postgresql"); Assert_Equals (T, "select count(*) from user", Query.Get_SQL (Manager)); exception when ADO.Queries.Query_Error => Count := Count + 1; end; T.Assert (Count > 0, "No Query_Error exception was raised"); end Test_Missing_Query; Q1 : aliased constant String := "<query-mapping><query name='internal-query'>" & "<sql>SELECT 'internal-query'</sql></query></query-mapping>"; function Loader (Name : in String) return access constant String is begin if Name = "regtests/files/internal-query.xml" then return Q1'Access; end if; return null; end Loader; -- ------------------------------ -- Test the static query loader. -- ------------------------------ procedure Test_Query_Loader (T : in out Test) is Query : ADO.Queries.Context; Manager : Query_Manager; Config : ADO.Connections.Configuration; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin Config.Set_Connection (Config_URL); Manager.Set_Query_Loader (Loader'Access); ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("internal-query"); Assert_Equals (T, "SELECT 'internal-query'", Query.Get_SQL (Manager)); end Test_Query_Loader; end ADO.Queries.Tests;
----------------------------------------------------------------------- -- ado-queries-tests -- Test loading of database queries -- 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 Util.Test_Caller; with ADO.Connections; with ADO.Queries.Loaders; package body ADO.Queries.Tests is use Util.Tests; Init_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => Ada.Calendar.Year_Number'First, Month => 1, Day => 1); function Loader (Name : in String) return access constant String; package Caller is new Util.Test_Caller (Test, "ADO.Queries"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query", Test_Load_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Find_Query", Test_Find_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Initialize", Test_Initialize'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Read_Query (reload)", Test_Reload_Queries'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query", Test_Set_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Limit", Test_Set_Limit'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Get_SQL (raise Query_Error)", Test_Missing_Query'Access); Caller.Add_Test (Suite, "Test ADO.Queries.Set_Query_Loader", Test_Query_Loader'Access); end Add_Tests; package Simple_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/simple-query.xml", Sha1 => ""); package Multi_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/multi-query.xml", Sha1 => ""); package Missing_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/missing-query.xml", Sha1 => ""); package Internal_Query_File is new ADO.Queries.Loaders.File (Path => "regtests/files/internal-query.xml", Sha1 => ""); package Simple_Query is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Simple_Query_File.File'Access); package Simple_Query_2 is new ADO.Queries.Loaders.Query (Name => "simple-query", File => Multi_Query_File.File'Access); package Index_Query is new ADO.Queries.Loaders.Query (Name => "index", File => Multi_Query_File.File'Access); package Value_Query is new ADO.Queries.Loaders.Query (Name => "value", File => Multi_Query_File.File'Access); package Internal_Query is new ADO.Queries.Loaders.Query (Name => "internal-query", File => Internal_Query_File.File'Access); package Missing_Query_SQLite is new ADO.Queries.Loaders.Query (Name => "missing-query-sqlite", File => Missing_Query_File.File'Access); package Missing_Query_MySQL is new ADO.Queries.Loaders.Query (Name => "missing-query-mysql", File => Missing_Query_File.File'Access); package Missing_Query_Postgresql is new ADO.Queries.Loaders.Query (Name => "missing-query-postgresql", File => Missing_Query_File.File'Access); package Missing_Query is new ADO.Queries.Loaders.Query (Name => "missing-query", File => Missing_Query_File.File'Access); pragma Warnings (Off, Simple_Query_2); pragma Warnings (Off, Value_Query); pragma Warnings (Off, Missing_Query); pragma Warnings (Off, Missing_Query_SQLite); pragma Warnings (Off, Missing_Query_MySQL); pragma Warnings (Off, Missing_Query_Postgresql); pragma Warnings (Off, Internal_Query); procedure Test_Load_Queries (T : in out Test) is use ADO.Connections; use type ADO.Configs.Driver_Index; Mysql_Driver : constant Driver_Access := ADO.Connections.Get_Driver ("mysql"); Sqlite_Driver : constant Driver_Access := ADO.Connections.Get_Driver ("sqlite"); Psql_Driver : constant Driver_Access := ADO.Connections.Get_Driver ("postgresql"); Config : ADO.Connections.Configuration; Manager : Query_Manager; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin -- Configure the XML query loader. Config.Set_Connection (Config_URL); ADO.Queries.Loaders.Initialize (Manager, Config); declare SQL : constant String := ADO.Queries.Get_SQL (Simple_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then Assert_Equals (T, "select 1", SQL, "Invalid query for 'index'"); elsif Psql_Driver /= null and then Manager.Driver = Psql_Driver.Get_Driver_Index then Assert_Equals (T, "select 3", SQL, "Invalid query for 'index'"); else Assert_Equals (T, "select 0", SQL, "Invalid query for 'index'"); end if; end; if Mysql_Driver /= null and then Manager.Driver = Mysql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 1", SQL, "Invalid query for 'index' (MySQL driver)"); end; end if; if Sqlite_Driver /= null and then Manager.Driver = Sqlite_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 0", SQL, "Invalid query for 'index' (SQLite driver)"); end; end if; if Psql_Driver /= null and then Manager.Driver = Psql_Driver.Get_Driver_Index then declare SQL : constant String := ADO.Queries.Get_SQL (Index_Query.Query'Access, Manager, False); begin Assert_Equals (T, "select 3", SQL, "Invalid query for 'index' (PostgreSQL driver)"); end; end if; end Test_Load_Queries; -- ------------------------------ -- Test re-loading queries. -- ------------------------------ procedure Test_Reload_Queries (T : in out Test) is Config : ADO.Connections.Configuration; Manager : Query_Manager; Query : ADO.Queries.Context; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin -- Configure the XML query loader. Config.Set_Connection (Config_URL); ADO.Queries.Loaders.Initialize (Manager, Config); for I in 1 .. 10 loop Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; for J in Manager.Files'Range loop Manager.Files (J).Next_Check := Init_Time; end loop; end loop; end Test_Reload_Queries; -- ------------------------------ -- Test the Initialize operation called several times -- ------------------------------ procedure Test_Initialize (T : in out Test) is Config : ADO.Connections.Configuration; Manager : Query_Manager; Pos : Query_Index; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin Config.Set_Connection (Config_URL); -- Configure and load the XML queries. for Pass in 1 .. 10 loop Config.Set_Property ("ado.queries.load", (if Pass = 1 then "false" else "true")); ADO.Queries.Loaders.Initialize (Manager, Config); T.Assert (Manager.Queries /= null, "The queries table is allocated"); T.Assert (Manager.Files /= null, "The files table is allocated"); Pos := 1; for Query of Manager.Queries.all loop if Pass = 1 then T.Assert (Query.Is_Null, "Query must not be loaded"); elsif Missing_Query.Query.Query /= Pos and Internal_Query.Query.Query /= Pos then T.Assert (not Query.Is_Null, "Query must have been loaded"); else T.Assert (Query.Is_Null, "Query must not be loaded (not found)"); end if; Pos := Pos + 1; end loop; end loop; end Test_Initialize; -- ------------------------------ -- Test the Set_Query operation. -- ------------------------------ procedure Test_Set_Query (T : in out Test) is Query : ADO.Queries.Context; Manager : Query_Manager; Config : ADO.Connections.Configuration; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin Config.Set_Connection (Config_URL); ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("simple-query"); declare SQL : constant String := Query.Get_SQL (Manager); begin Assert_Equals (T, "select count(*) from user", SQL, "Invalid query for 'simple-query'"); end; end Test_Set_Query; -- ------------------------------ -- Test the Set_Limit operation. -- ------------------------------ procedure Test_Set_Limit (T : in out Test) is Query : ADO.Queries.Context; begin Query.Set_Query ("index"); Query.Set_Limit (0, 10); Assert_Equals (T, 0, Query.Get_First_Row_Index, "Invalid first row index"); Assert_Equals (T, 10, Query.Get_Last_Row_Index, "Invalid last row index"); end Test_Set_Limit; -- ------------------------------ -- Test the Find_Query operation. -- ------------------------------ procedure Test_Find_Query (T : in out Test) is Q : Query_Definition_Access; begin Q := ADO.Queries.Loaders.Find_Query ("this query does not exist"); T.Assert (Q = null, "Find_Query should return null for unkown query"); end Test_Find_Query; -- ------------------------------ -- Test the missing query. -- ------------------------------ procedure Test_Missing_Query (T : in out Test) is Query : ADO.Queries.Context; Manager : Query_Manager; Config : ADO.Connections.Configuration; Count : Natural := 0; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin Config.Set_Connection (Config_URL); ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("missing-query"); begin Assert_Equals (T, "?", Query.Get_SQL (Manager)); T.Fail ("No ADO.Queries.Query_Error exception was raised"); exception when ADO.Queries.Query_Error => null; end; begin Query.Set_Query ("missing-query-sqlite"); Assert_Equals (T, "select count(*) from user", Query.Get_SQL (Manager)); exception when ADO.Queries.Query_Error => Count := Count + 1; end; begin Query.Set_Query ("missing-query-mysql"); Assert_Equals (T, "select count(*) from user", Query.Get_SQL (Manager)); exception when ADO.Queries.Query_Error => Count := Count + 1; end; begin Query.Set_Query ("missing-query-postgresql"); Assert_Equals (T, "select count(*) from user", Query.Get_SQL (Manager)); exception when ADO.Queries.Query_Error => Count := Count + 1; end; T.Assert (Count > 0, "No Query_Error exception was raised"); end Test_Missing_Query; Q1 : aliased constant String := "<query-mapping><query name='internal-query'>" & "<sql>SELECT 'internal-query'</sql></query></query-mapping>"; function Loader (Name : in String) return access constant String is begin if Name = "regtests/files/internal-query.xml" then return Q1'Access; end if; return null; end Loader; -- ------------------------------ -- Test the static query loader. -- ------------------------------ procedure Test_Query_Loader (T : in out Test) is Query : ADO.Queries.Context; Manager : Query_Manager; Config : ADO.Connections.Configuration; Config_URL : constant String := Util.Tests.Get_Parameter ("test.database", "sqlite:///regtests.db"); begin Config.Set_Connection (Config_URL); Manager.Set_Query_Loader (Loader'Access); ADO.Queries.Loaders.Initialize (Manager, Config); Query.Set_Query ("internal-query"); Assert_Equals (T, "SELECT 'internal-query'", Query.Get_SQL (Manager)); end Test_Query_Loader; end ADO.Queries.Tests;
Update unit test to use a Ada.Calendar.Time
Update unit test to use a Ada.Calendar.Time
Ada
apache-2.0
stcarrez/ada-ado
8a3450eab40ff32b351c4c8869f3085a99c3eb3c
matp/src/symbols/mat-symbols-targets.adb
matp/src/symbols/mat-symbols-targets.adb
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- 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 Bfd.Sections; with ELF; with Util.Strings; with Util.Files; with Util.Log.Loggers; with Ada.Directories; with MAT.Formats; package body MAT.Symbols.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets"); -- ------------------------------ -- Open the binary and load the symbols from that file. -- ------------------------------ procedure Open (Symbols : in out Target_Symbols; Path : in String) is begin Log.Info ("Loading symbols from {0}", Path); -- -- Bfd.Files.Open (Symbols.File, Path, ""); -- if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then -- Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); -- end if; end Open; -- ------------------------------ -- Load the symbol table for the associated region. -- ------------------------------ procedure Open (Symbols : in out Region_Symbols; Path : in String; Search_Path : in String) is Pos : Natural; begin Log.Info ("Loading symbols from {0}", Path); if Ada.Directories.Exists (Path) then Bfd.Files.Open (Symbols.File, Path, ""); else Pos := Util.Strings.Rindex (Path, '/'); if Pos > 0 then Bfd.Files.Open (Symbols.File, Util.Files.Find_File_Path (Path (Pos + 1 .. Path'Last), Search_Path)); end if; end if; if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); end if; end Open; -- ------------------------------ -- Load the symbols associated with a shared library described by the memory region. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr) is use type Bfd.File_Flags; Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr); Syms : Region_Symbols_Ref; begin if not Symbols_Maps.Has_Element (Pos) then Syms := Region_Symbols_Refs.Create; Syms.Value.Region := Region; Syms.Value.Offset := Offset_Addr; Symbols.Libraries.Insert (Region.Start_Addr, Syms); else Syms := Symbols_Maps.Element (Pos); end if; if Ada.Strings.Unbounded.Length (Region.Path) > 0 then Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path), Ada.Strings.Unbounded.To_String (Symbols.Search_Path)); if (Bfd.Files.Get_File_Flags (Syms.Value.File) and Bfd.Files.EXEC_P) /= 0 then Syms.Value.Offset := 0; end if; end if; end Load_Symbols; -- ------------------------------ -- Load the symbols associated with all the shared libraries described by -- the memory region map. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Regions : in MAT.Memory.Region_Info_Map) is use type ELF.Elf32_Word; Iter : MAT.Memory.Region_Info_Cursor := Regions.First; begin while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop declare Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter); Offset : MAT.Types.Target_Addr; begin if (Region.Flags and ELF.PF_X) /= 0 then if Ada.Strings.Unbounded.Length (Region.Path) = 0 then Region.Path := Symbols.Path; Offset := 0; else Offset := Region.Start_Addr; end if; MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset); end if; exception when Bfd.OPEN_ERROR => Symbols.Console.Error ("Cannot open symbol library file '" & Ada.Strings.Unbounded.To_String (Region.Path) & "'"); end; MAT.Memory.Region_Info_Maps.Next (Iter); end loop; end Load_Symbols; -- ------------------------------ -- Demangle the symbol. -- ------------------------------ procedure Demangle (Symbols : in Target_Symbols; Symbol : in out Symbol_Info) is use type Bfd.Demangle_Flags; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward); begin if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then return; end if; declare Mode : Bfd.Demangle_Flags := Symbols.Demangle; Len : constant Positive := Length (Symbol.File); Ext : constant String := Slice (Symbol.File, Pos, Len); Sym : constant String := To_String (Symbol.Name); begin if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then Mode := Bfd.Constants.DMGL_GNAT; end if; declare Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode); begin if Name'Length > 0 then Symbol.Name := To_Unbounded_String (Name); end if; end; end; end Demangle; procedure Find_Nearest_Line (Symbols : in Region_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info) is use type Bfd.Vma_Type; Text_Section : Bfd.Sections.Section; Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr); begin if not Bfd.Files.Is_Open (Symbols.File) then Symbol.File := Symbols.Region.Path; return; end if; Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text"); Bfd.Symbols.Find_Nearest_Line (File => Symbols.File, Sec => Text_Section, Symbols => Symbols.Symbols, Addr => Pc, Name => Symbol.File, Func => Symbol.Name, Line => Symbol.Line); end Find_Nearest_Line; -- ------------------------------ -- Find the nearest source file and line for the given address. -- ------------------------------ procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info) is use Ada.Strings.Unbounded; Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr); begin Symbol.Line := 0; if Symbols_Maps.Has_Element (Pos) then declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos); begin if Syms.Value.Region.End_Addr > Addr then Symbol.Symbols := Syms; Find_Nearest_Line (Symbols => Syms.Value.all, Addr => Addr - Syms.Value.Offset, Symbol => Symbol); Demangle (Symbols, Symbol); return; end if; end; end if; Symbol.Line := 0; Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String (""); Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr)); exception when Bfd.NOT_FOUND => Symbol.Line := 0; Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String (""); Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr)); end Find_Nearest_Line; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ procedure Find_Symbol_Range (Symbols : in Target_Symbols; Name : in String; From : out MAT.Types.Target_Addr; To : out MAT.Types.Target_Addr) is use type Bfd.Symbols.Symbol; Iter : Symbols_Cursor := Symbols.Libraries.First; begin while Symbols_Maps.Has_Element (Iter) loop declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter); Sym : Bfd.Symbols.Symbol; Sec : Bfd.Sections.Section; begin if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name); if Sym /= Bfd.Symbols.Null_Symbol then Sec := Bfd.Symbols.Get_Section (Sym); if not Bfd.Sections.Is_Undefined_Section (Sec) then From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym)); From := From + Syms.Value.Offset; To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym)); return; end if; end if; end if; end; Symbols_Maps.Next (Iter); end loop; end Find_Symbol_Range; end MAT.Symbols.Targets;
----------------------------------------------------------------------- -- mat-symbols-targets - Symbol files management -- Copyright (C) 2014, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Bfd.Sections; with ELF; with Util.Strings; with Util.Files; with Util.Log.Loggers; with Ada.Directories; with MAT.Formats; package body MAT.Symbols.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets"); procedure Find_Nearest_Line (Symbols : in Region_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info); -- ------------------------------ -- Open the binary and load the symbols from that file. -- ------------------------------ procedure Open (Symbols : in out Target_Symbols; Path : in String) is begin Log.Info ("Loading symbols from {0}", Path); -- -- Bfd.Files.Open (Symbols.File, Path, ""); -- if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then -- Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); -- end if; end Open; -- ------------------------------ -- Load the symbol table for the associated region. -- ------------------------------ procedure Open (Symbols : in out Region_Symbols; Path : in String; Search_Path : in String) is Pos : Natural; begin Log.Info ("Loading symbols from {0}", Path); if Ada.Directories.Exists (Path) then Bfd.Files.Open (Symbols.File, Path, ""); else Pos := Util.Strings.Rindex (Path, '/'); if Pos > 0 then Bfd.Files.Open (Symbols.File, Util.Files.Find_File_Path (Path (Pos + 1 .. Path'Last), Search_Path)); end if; end if; if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols); end if; end Open; -- ------------------------------ -- Load the symbols associated with a shared library described by the memory region. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Region : in MAT.Memory.Region_Info; Offset_Addr : in MAT.Types.Target_Addr) is use type Bfd.File_Flags; Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr); Syms : Region_Symbols_Ref; begin if not Symbols_Maps.Has_Element (Pos) then Syms := Region_Symbols_Refs.Create; Syms.Value.Region := Region; Syms.Value.Offset := Offset_Addr; Symbols.Libraries.Insert (Region.Start_Addr, Syms); else Syms := Symbols_Maps.Element (Pos); end if; if Ada.Strings.Unbounded.Length (Region.Path) > 0 then Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path), Ada.Strings.Unbounded.To_String (Symbols.Search_Path)); if (Bfd.Files.Get_File_Flags (Syms.Value.File) and Bfd.Files.EXEC_P) /= 0 then Syms.Value.Offset := 0; end if; end if; end Load_Symbols; -- ------------------------------ -- Load the symbols associated with all the shared libraries described by -- the memory region map. -- ------------------------------ procedure Load_Symbols (Symbols : in out Target_Symbols; Regions : in MAT.Memory.Region_Info_Map) is use type ELF.Elf32_Word; Iter : MAT.Memory.Region_Info_Cursor := Regions.First; begin while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop declare Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter); Offset : MAT.Types.Target_Addr; begin if (Region.Flags and ELF.PF_X) /= 0 then if Ada.Strings.Unbounded.Length (Region.Path) = 0 then Region.Path := Symbols.Path; Offset := 0; else Offset := Region.Start_Addr; end if; MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset); end if; exception when Bfd.OPEN_ERROR => Symbols.Console.Error ("Cannot open symbol library file '" & Ada.Strings.Unbounded.To_String (Region.Path) & "'"); end; MAT.Memory.Region_Info_Maps.Next (Iter); end loop; end Load_Symbols; -- ------------------------------ -- Demangle the symbol. -- ------------------------------ procedure Demangle (Symbols : in Target_Symbols; Symbol : in out Symbol_Info) is use type Bfd.Demangle_Flags; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward); begin if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then return; end if; declare Mode : Bfd.Demangle_Flags := Symbols.Demangle; Len : constant Positive := Length (Symbol.File); Ext : constant String := Slice (Symbol.File, Pos, Len); Sym : constant String := To_String (Symbol.Name); begin if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then Mode := Bfd.Constants.DMGL_GNAT; end if; declare Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode); begin if Name'Length > 0 then Symbol.Name := To_Unbounded_String (Name); end if; end; end; end Demangle; procedure Find_Nearest_Line (Symbols : in Region_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info) is Text_Section : Bfd.Sections.Section; Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr); begin if not Bfd.Files.Is_Open (Symbols.File) then Symbol.File := Symbols.Region.Path; return; end if; Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text"); Bfd.Symbols.Find_Nearest_Line (File => Symbols.File, Sec => Text_Section, Symbols => Symbols.Symbols, Addr => Pc, Name => Symbol.File, Func => Symbol.Name, Line => Symbol.Line); end Find_Nearest_Line; -- ------------------------------ -- Find the nearest source file and line for the given address. -- ------------------------------ procedure Find_Nearest_Line (Symbols : in Target_Symbols; Addr : in MAT.Types.Target_Addr; Symbol : out Symbol_Info) is Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr); begin Symbol.Line := 0; if Symbols_Maps.Has_Element (Pos) then declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos); begin if Syms.Value.Region.End_Addr > Addr then Symbol.Symbols := Syms; Find_Nearest_Line (Symbols => Syms.Value.all, Addr => Addr - Syms.Value.Offset, Symbol => Symbol); Demangle (Symbols, Symbol); return; end if; end; end if; Symbol.Line := 0; Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String (""); Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr)); exception when Bfd.NOT_FOUND => Symbol.Line := 0; Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String (""); Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr)); end Find_Nearest_Line; -- ------------------------------ -- Find the symbol in the symbol table and return the start and end address. -- ------------------------------ procedure Find_Symbol_Range (Symbols : in Target_Symbols; Name : in String; From : out MAT.Types.Target_Addr; To : out MAT.Types.Target_Addr) is use type Bfd.Symbols.Symbol; Iter : Symbols_Cursor := Symbols.Libraries.First; begin while Symbols_Maps.Has_Element (Iter) loop declare Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter); Sym : Bfd.Symbols.Symbol; Sec : Bfd.Sections.Section; begin if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name); if Sym /= Bfd.Symbols.Null_Symbol then Sec := Bfd.Symbols.Get_Section (Sym); if not Bfd.Sections.Is_Undefined_Section (Sec) then From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym)); From := From + Syms.Value.Offset; To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym)); return; end if; end if; end if; end; Symbols_Maps.Next (Iter); end loop; end Find_Symbol_Range; end MAT.Symbols.Targets;
Fix compilation warning with GNAT 2018
Fix compilation warning with GNAT 2018
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
5a295f21844464f1847b7041accbaf674ac1719d
boards/MicroBit/src/microbit-i2c.adb
boards/MicroBit/src/microbit-i2c.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2018, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with nRF51.Device; with nRF51.TWI; package body MicroBit.I2C is Init_Done : Boolean := False; ----------------- -- Initialized -- ----------------- function Initialized return Boolean is (Init_Done); ---------------- -- Initialize -- ---------------- procedure Initialize (S : Speed := S400kbps) is begin nRF51.Device.TWI_0.Configure (SCL => MB_SCL.Pin, SDA => MB_SDA.Pin, Speed => (case S is when S100kbps => nRF51.TWI.TWI_100kbps, when S250kbps => nRF51.TWI.TWI_250kbps, when S400kbps => nRF51.TWI.TWI_400kbps) ); nRF51.Device.TWI_0.Enable; Init_Done := True; end Initialize; ---------------- -- Controller -- ---------------- function Controller return not null Any_I2C_Port is (nRF51.Device.TWI_0'Access); end MicroBit.I2C;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2018, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with nRF51.Device; with nRF51.TWI; package body MicroBit.I2C is Init_Done : Boolean := False; Device : nRF51.TWI.TWI_Master renames nRF51.Device.TWI_0; -- This device should not conflict with the device used in MicroBit.SPI. -- See nRF51 Series Reference Manual, chapter Memory.Instantiation. ----------------- -- Initialized -- ----------------- function Initialized return Boolean is (Init_Done); ---------------- -- Initialize -- ---------------- procedure Initialize (S : Speed := S400kbps) is begin Device.Configure (SCL => MB_SCL.Pin, SDA => MB_SDA.Pin, Speed => (case S is when S100kbps => nRF51.TWI.TWI_100kbps, when S250kbps => nRF51.TWI.TWI_250kbps, when S400kbps => nRF51.TWI.TWI_400kbps) ); Device.Enable; Init_Done := True; end Initialize; ---------------- -- Controller -- ---------------- function Controller return not null Any_I2C_Port is (Device'Access); end MicroBit.I2C;
clean up device definition
MicroBit.I2C: clean up device definition
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
92547bebfc0b5119cddd71cd7a2433c178ddbb1e
src/gen-commands-plugins.adb
src/gen-commands-plugins.adb
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- Copyright (C) 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with Gen.Model.Projects; with GNAT.Command_Line; with Util.Files; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Plugins is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ -- 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; function Get_Directory_Name (Name : in String; Name_Dir : in Ada.Strings.Unbounded.Unbounded_String) return String; function Get_Directory_Name (Name : in String; Name_Dir : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (Name_Dir) = 0 then return Name; else return Ada.Strings.Unbounded.To_String (Name_Dir); end if; end Get_Directory_Name; Result_Dir : constant String := Generator.Get_Result_Directory; Name_Dir : Ada.Strings.Unbounded.Unbounded_String; 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: d:") is when ASCII.NUL => exit; when 'd' => Name_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); 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; declare Name : constant String := Get_Argument; Kind : constant String := Get_Argument; Dir : constant String := Generator.Get_Plugin_Directory; Path : constant String := Util.Files.Compose (Dir, Get_Directory_Name (Name, Name_Dir)); begin if Name'Length = 0 then Generator.Error ("Missing plugin name"); Gen.Commands.Usage; return; end if; if Kind /= "ada" and Kind /= "web" then Generator.Error ("Invalid plugin type (must be 'ada' or 'web')"); return; end if; if Ada.Directories.Exists (Path) then Generator.Error ("Plugin {0} exists already", Name); return; end if; if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Directory (Dir); end if; Ada.Directories.Create_Directory (Path); Generator.Set_Result_Directory (Path); -- Create the plugin project instance and generate its dynamo.xml file. -- The new plugin is added to the current project so that it will be referenced. declare procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition); procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is Plugin : Gen.Model.Projects.Project_Definition_Access; File : constant String := Util.Files.Compose (Path, "dynamo.xml"); begin Project.Create_Project (Name => Name, Path => File, Project => Plugin); Project.Add_Module (Plugin); Plugin.Props.Set ("license", Project.Props.Get ("license", "none")); Plugin.Props.Set ("author", Project.Props.Get ("author", "")); Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", "")); Plugin.Save (File); end Create_Plugin; begin Generator.Update_Project (Create_Plugin'Access); end; -- Generate the new plugin content. Generator.Set_Force_Save (False); Generator.Set_Global ("pluginName", Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin-" & Kind); -- And save the project dynamo.xml file which now refers to the new plugin. Generator.Set_Result_Directory (Result_Dir); Generator.Save_Project; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => Generator.Error ("Cannot create directory {0}", Path); 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-plugin: Create a new plugin for the current project"); Put_Line ("Usage: create-plugin [-l apache|gpl|gpl3|mit|bsd3|proprietary] " & "[-d DIR] NAME [ada | web]"); New_Line; Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME."); Put_Line (" The plugin license is controlled by the -l option."); Put_Line (" The plugin type is specified as the last argument which can be one of:"); New_Line; Put_Line (" ada the plugin contains Ada code and a GNAT project is created"); Put_Line (" web the plugin contains XHTML, CSS, Javascript files only"); New_Line; Put_Line (" The -d option allows to control the plugin directory name. The plugin NAME"); Put_Line (" is used by default. The plugin is created in the directory:"); Put_Line (" plugins/NAME or plugins/DIR"); New_Line; Put_Line (" For the Ada plugin, the command generates the following files" & " in the plugin directory:"); Put_Line (" src/<project>-<plugin>.ads"); Put_Line (" src/<project>-<plugin>-<module>.ads"); Put_Line (" src/<project>-<plugin>-<module>.adb"); end Help; end Gen.Commands.Plugins;
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- Copyright (C) 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with Gen.Model.Projects; with GNAT.Command_Line; with Util.Files; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Plugins is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ -- Execute the command with the arguments. overriding procedure Execute (Cmd : in Command; Name : in String; Args : in Argument_List'Class; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; function Get_Directory_Name (Name : in String; Name_Dir : in Ada.Strings.Unbounded.Unbounded_String) return String; function Get_Directory_Name (Name : in String; Name_Dir : in Ada.Strings.Unbounded.Unbounded_String) return String is begin if Ada.Strings.Unbounded.Length (Name_Dir) = 0 then return Name; else return Ada.Strings.Unbounded.To_String (Name_Dir); end if; end Get_Directory_Name; Result_Dir : constant String := Generator.Get_Result_Directory; Name_Dir : Ada.Strings.Unbounded.Unbounded_String; 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: d:") is when ASCII.NUL => exit; when 'd' => Name_Dir := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); 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; declare Name : constant String := Get_Argument; Kind : constant String := Get_Argument; Dir : constant String := Generator.Get_Plugin_Directory; Path : constant String := Util.Files.Compose (Dir, Get_Directory_Name (Name, Name_Dir)); begin if Name'Length = 0 then Generator.Error ("Missing plugin name"); Gen.Commands.Usage; return; end if; if Kind /= "ada" and Kind /= "web" then Generator.Error ("Invalid plugin type (must be 'ada' or 'web')"); return; end if; if Ada.Directories.Exists (Path) then Generator.Error ("Plugin {0} exists already", Name); return; end if; if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Directory (Dir); end if; Ada.Directories.Create_Directory (Path); Generator.Set_Result_Directory (Path); -- Create the plugin project instance and generate its dynamo.xml file. -- The new plugin is added to the current project so that it will be referenced. declare procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition); procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is Plugin : Gen.Model.Projects.Project_Definition_Access; File : constant String := Util.Files.Compose (Path, "dynamo.xml"); begin Project.Create_Project (Name => Name, Path => File, Project => Plugin); Project.Add_Module (Plugin); Plugin.Props.Set ("license", Project.Props.Get ("license", "none")); Plugin.Props.Set ("author", Project.Props.Get ("author", "")); Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", "")); Plugin.Save (File); end Create_Plugin; begin Generator.Update_Project (Create_Plugin'Access); end; -- Generate the new plugin content. Generator.Set_Force_Save (False); Generator.Set_Global ("pluginName", Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin-" & Kind); -- And save the project dynamo.xml file which now refers to the new plugin. Generator.Set_Result_Directory (Result_Dir); Generator.Save_Project; exception when Ada.Directories.Name_Error | Ada.Directories.Use_Error => Generator.Error ("Cannot create directory {0}", Path); 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-plugin: Create a new plugin for the current project"); Put_Line ("Usage: create-plugin [-l apache|gpl|gpl3|mit|bsd3|proprietary] " & "[-d DIR] NAME [ada | web]"); New_Line; Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME."); Put_Line (" The plugin license is controlled by the -l option."); Put_Line (" The plugin type is specified as the last argument which can be one of:"); New_Line; Put_Line (" ada the plugin contains Ada code and a GNAT project is created"); Put_Line (" web the plugin contains XHTML, CSS, Javascript files only"); New_Line; Put_Line (" The -d option allows to control the plugin directory name. The plugin NAME"); Put_Line (" is used by default. The plugin is created in the directory:"); Put_Line (" plugins/NAME or plugins/DIR"); New_Line; Put_Line (" For the Ada plugin, the command generates the following files" & " in the plugin directory:"); Put_Line (" src/<project>-<plugin>.ads"); Put_Line (" src/<project>-<plugin>-<module>.ads"); Put_Line (" src/<project>-<plugin>-<module>.adb"); end Help; end Gen.Commands.Plugins;
Update to use the new command implementation
Update to use the new command implementation
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo