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
e922080e8a6d09816715e208910ea1918ea995fb
mat/src/mat-readers-streams.adb
mat/src/mat-readers-streams.adb
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.IO_Exceptions; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Read a message from the stream. -- ------------------------------ overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message) is use type Ada.Streams.Stream_Element_Offset; Buffer : constant Util.Streams.Buffered.Buffer_Access := Msg.Buffer.Buffer; Last : Ada.Streams.Stream_Element_Offset; begin Reader.Stream.Read (Buffer (0 .. 1), Last); if Last /= 2 then raise Ada.IO_Exceptions.End_Error; end if; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Buffer'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); raise Ada.IO_Exceptions.Data_Error; end if; Reader.Stream.Read (Buffer (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Buffer (Last)'Address; Msg.Buffer.Size := Msg.Size; end Read_Message; -- ------------------------------ -- Read the events from the stream and stop when the end of the stream is reached. -- ------------------------------ procedure Read_All (Reader : in out Stream_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Data : aliased Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (MAX_MSG_SIZE)'Address; Msg.Buffer.Size := 3; Reader.Stream.Read (Data (0 .. 2), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (Last)'Address; Msg.Buffer.Size := Msg.Size; Reader.Read_Headers (Msg); while not Reader.Stream.Is_Eof loop Reader.Stream.Read (Data (0 .. 1), Last); exit when Last /= 2; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Data'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); exit; end if; Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (Last)'Address; Msg.Buffer.Size := Msg.Size; Reader.Dispatch_Message (Msg); end loop; end Read_All; end MAT.Readers.Streams;
----------------------------------------------------------------------- -- mat-readers-streams -- Reader for streams -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.IO_Exceptions; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Streams is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- ------------------------------ -- Read a message from the stream. -- ------------------------------ overriding procedure Read_Message (Reader : in out Stream_Reader_Type; Msg : in out Message) is use type Ada.Streams.Stream_Element_Offset; Buffer : constant Util.Streams.Buffered.Buffer_Access := Msg.Buffer.Buffer; Last : Ada.Streams.Stream_Element_Offset; begin Reader.Stream.Read (Buffer (0 .. 1), Last); if Last /= 2 then raise Ada.IO_Exceptions.End_Error; end if; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Buffer'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); raise Ada.IO_Exceptions.Data_Error; end if; Reader.Stream.Read (Buffer (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Buffer (Last)'Address; Msg.Buffer.Size := Msg.Size; end Read_Message; -- ------------------------------ -- Read the events from the stream and stop when the end of the stream is reached. -- ------------------------------ procedure Read_All (Reader : in out Stream_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Reader.Data := new Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Reader.Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Reader.Data (MAX_MSG_SIZE)'Address; Msg.Buffer.Size := 3; Buffer.Buffer := Reader.Data; Reader.Stream.Read (Reader.Data (0 .. 2), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Reader.Read_Message (Msg); Reader.Read_Headers (Msg); while not Reader.Stream.Is_Eof loop Reader.Read_Message (Msg); Reader.Dispatch_Message (Msg); end loop; end Read_All; end MAT.Readers.Streams;
Use Read_Message to read the message in Read_All procedure
Use Read_Message to read the message in Read_All procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b565ef756f38f20899c9e3815f3811ee25a12411
src/os-none/util-processes-os.ads
src/os-none/util-processes-os.ads
----------------------------------------------------------------------- -- util-processes-os -- System specific and low level operations -- 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. ----------------------------------------------------------------------- private package Util.Processes.Os is -- Wait for the process <b>Pid</b> to finish and return the process exit status. procedure Waitpid (Pid : in Process_Identifier; Status : out Integer); -- Spawn a process procedure Spawn (Proc : in out Process; Mode : in Pipe_Mode := NONE); end Util.Processes.Os;
----------------------------------------------------------------------- -- util-processes-os -- Dummy system specific and low level operations -- 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. ----------------------------------------------------------------------- private package Util.Processes.Os is -- Wait for the process <b>Pid</b> to finish and return the process exit status. procedure Waitpid (Pid : in Process_Identifier; Status : out Integer); -- Spawn a process procedure Spawn (Proc : in out Process; Mode : in Pipe_Mode := NONE); end Util.Processes.Os;
Update comment title
Update comment title
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
861790b458ce51db0affb10ed52e27046f2fda2e
regtests/util-log-tests.ads
regtests/util-log-tests.ads
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2015, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Log.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Log_Perf (T : in out Test); procedure Test_Log (T : in out Test); procedure Test_File_Appender (T : in out Test); procedure Test_List_Appender (T : in out Test); procedure Test_Console_Appender (T : in out Test); procedure Test_Missing_Config (T : in out Test); -- Test file appender with different modes. procedure Test_File_Appender_Modes (T : in out Test); end Util.Log.Tests;
----------------------------------------------------------------------- -- log.tests -- Unit tests for loggers -- Copyright (C) 2009, 2010, 2011, 2015, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Log.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Log_Perf (T : in out Test); procedure Test_Log (T : in out Test); procedure Test_File_Appender (T : in out Test); procedure Test_List_Appender (T : in out Test); procedure Test_Console_Appender (T : in out Test); procedure Test_Missing_Config (T : in out Test); procedure Test_Log_Traceback (T : in out Test); -- Test file appender with different modes. procedure Test_File_Appender_Modes (T : in out Test); end Util.Log.Tests;
Declare Test_Log_Traceback procedure
Declare Test_Log_Traceback procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
499795d4d9871e398eab516aaaec45bb2e808d57
src/el-contexts-default.adb
src/el-contexts-default.adb
----------------------------------------------------------------------- -- EL.Contexts -- Default contexts for evaluating an expression -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with EL.Variables.Default; package body EL.Contexts.Default is procedure Free is new Ada.Unchecked_Deallocation (Object => EL.Variables.Variable_Mapper'Class, Name => EL.Variables.Variable_Mapper_Access); -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : Default_Context) return ELResolver_Access is begin return Context.Resolver; end Get_Resolver; -- ------------------------------ -- Set the ELResolver associated with this ELcontext. -- ------------------------------ procedure Set_Resolver (Context : in out Default_Context; Resolver : in ELResolver_Access) is begin Context.Resolver := Resolver; end Set_Resolver; -- ------------------------------ -- Retrieves the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : Default_Context) return access EL.Variables.Variable_Mapper'Class is begin return Context.Var_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the Function_Mapper associated with this ELContext. -- The Function_Mapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : Default_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Default_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin if Mapper = null then Context.Function_Mapper := null; else Context.Function_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Function_Mapper; -- ------------------------------ -- Set the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Default_Context; Mapper : access EL.Variables.Variable_Mapper'Class) is use EL.Variables; begin if Context.Var_Mapper_Created then Free (Context.Var_Mapper); end if; if Mapper = null then Context.Var_Mapper := null; else Context.Var_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Variable_Mapper; procedure Set_Variable (Context : in out Default_Context; Name : in String; Value : access Util.Beans.Basic.Readonly_Bean'Class) is use EL.Variables; begin if Context.Var_Mapper = null then Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper; Context.Var_Mapper_Created := True; end if; Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value, EL.Objects.STATIC)); end Set_Variable; -- Handle the exception during expression evaluation. overriding procedure Handle_Exception (Context : in Default_Context; Ex : in Ada.Exceptions.Exception_Occurrence) is begin null; end Handle_Exception; -- ------------------------------ -- Guarded Context -- ------------------------------ -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : in Guarded_Context) return ELResolver_Access is begin return Context.Context.Get_Resolver; end Get_Resolver; -- ------------------------------ -- Retrieves the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : in Guarded_Context) return access EL.Variables.Variable_Mapper'Class is begin return Context.Context.Get_Variable_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the Function_Mapper associated with this ELContext. -- The Function_Mapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : in Guarded_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Context.Get_Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Guarded_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin Context.Context.Set_Function_Mapper (Mapper); end Set_Function_Mapper; -- ------------------------------ -- Set the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Guarded_Context; Mapper : access EL.Variables.Variable_Mapper'Class) is begin Context.Context.Set_Variable_Mapper (Mapper); end Set_Variable_Mapper; -- ------------------------------ -- Handle the exception during expression evaluation. -- ------------------------------ overriding procedure Handle_Exception (Context : in Guarded_Context; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Context.Handler.all (Ex); end Handle_Exception; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Default_ELResolver; Context : ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Object is pragma Unreferenced (Context); begin if Base /= null then return Base.Get_Value (To_String (Name)); end if; declare Pos : constant Objects.Maps.Cursor := Resolver.Map.Find (Name); begin if Objects.Maps.Has_Element (Pos) then return Objects.Maps.Element (Pos); end if; end; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in out Default_ELResolver; Context : in ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Object) is begin null; end Set_Value; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : access Util.Beans.Basic.Readonly_Bean'Class) is begin Resolver.Register (Name, To_Object (Value)); end Register; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin Objects.Maps.Include (Resolver.Map, Name, Value); end Register; overriding procedure Finalize (Obj : in out Default_Context) is begin if Obj.Var_Mapper_Created then Free (Obj.Var_Mapper); end if; end Finalize; end EL.Contexts.Default;
----------------------------------------------------------------------- -- EL.Contexts -- Default contexts for evaluating an expression -- 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.Unchecked_Deallocation; with EL.Variables.Default; package body EL.Contexts.Default is procedure Free is new Ada.Unchecked_Deallocation (Object => EL.Variables.Variable_Mapper'Class, Name => EL.Variables.Variable_Mapper_Access); -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : Default_Context) return ELResolver_Access is begin return Context.Resolver; end Get_Resolver; -- ------------------------------ -- Set the ELResolver associated with this ELcontext. -- ------------------------------ procedure Set_Resolver (Context : in out Default_Context; Resolver : in ELResolver_Access) is begin Context.Resolver := Resolver; end Set_Resolver; -- ------------------------------ -- Retrieves the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : Default_Context) return access EL.Variables.Variable_Mapper'Class is begin return Context.Var_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the Function_Mapper associated with this ELContext. -- The Function_Mapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : Default_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Default_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin if Mapper = null then Context.Function_Mapper := null; else Context.Function_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Function_Mapper; -- ------------------------------ -- Set the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Default_Context; Mapper : access EL.Variables.Variable_Mapper'Class) is use EL.Variables; begin if Context.Var_Mapper_Created then Free (Context.Var_Mapper); end if; if Mapper = null then Context.Var_Mapper := null; else Context.Var_Mapper := Mapper.all'Unchecked_Access; end if; end Set_Variable_Mapper; procedure Set_Variable (Context : in out Default_Context; Name : in String; Value : access Util.Beans.Basic.Readonly_Bean'Class) is use EL.Variables; begin if Context.Var_Mapper = null then Context.Var_Mapper := new EL.Variables.Default.Default_Variable_Mapper; Context.Var_Mapper_Created := True; end if; Context.Var_Mapper.Bind (Name, EL.Objects.To_Object (Value, EL.Objects.STATIC)); end Set_Variable; -- Handle the exception during expression evaluation. overriding procedure Handle_Exception (Context : in Default_Context; Ex : in Ada.Exceptions.Exception_Occurrence) is begin null; end Handle_Exception; -- ------------------------------ -- Guarded Context -- ------------------------------ -- ------------------------------ -- Retrieves the ELResolver associated with this ELcontext. -- ------------------------------ overriding function Get_Resolver (Context : in Guarded_Context) return ELResolver_Access is begin return Context.Context.Get_Resolver; end Get_Resolver; -- ------------------------------ -- Retrieves the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding function Get_Variable_Mapper (Context : in Guarded_Context) return access EL.Variables.Variable_Mapper'Class is begin return Context.Context.Get_Variable_Mapper; end Get_Variable_Mapper; -- ------------------------------ -- Retrieves the Function_Mapper associated with this ELContext. -- The Function_Mapper is only used when parsing an expression. -- ------------------------------ overriding function Get_Function_Mapper (Context : in Guarded_Context) return EL.Functions.Function_Mapper_Access is begin return Context.Context.Get_Function_Mapper; end Get_Function_Mapper; -- ------------------------------ -- Set the function mapper to be used when parsing an expression. -- ------------------------------ overriding procedure Set_Function_Mapper (Context : in out Guarded_Context; Mapper : access EL.Functions.Function_Mapper'Class) is begin Context.Context.Set_Function_Mapper (Mapper); end Set_Function_Mapper; -- ------------------------------ -- Set the Variable_Mapper associated with this ELContext. -- ------------------------------ overriding procedure Set_Variable_Mapper (Context : in out Guarded_Context; Mapper : access EL.Variables.Variable_Mapper'Class) is begin Context.Context.Set_Variable_Mapper (Mapper); end Set_Variable_Mapper; -- ------------------------------ -- Handle the exception during expression evaluation. -- ------------------------------ overriding procedure Handle_Exception (Context : in Guarded_Context; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Context.Handler.all (Ex); end Handle_Exception; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : Default_ELResolver; Context : ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : Unbounded_String) return Object is pragma Unreferenced (Context); Key : constant String := To_String (Name); begin if Base /= null then return Base.Get_Value (Key); end if; declare Pos : constant Objects.Maps.Cursor := Resolver.Map.Find (Key); begin if Objects.Maps.Has_Element (Pos) then return Objects.Maps.Element (Pos); end if; end; return Util.Beans.Objects.Null_Object; end Get_Value; -- ------------------------------ -- Set the value associated with a base object and a given property. -- ------------------------------ overriding procedure Set_Value (Resolver : in out Default_ELResolver; Context : in ELContext'Class; Base : access Util.Beans.Basic.Bean'Class; Name : in Unbounded_String; Value : in Object) is begin null; end Set_Value; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : access Util.Beans.Basic.Readonly_Bean'Class) is begin Resolver.Register (Name, To_Object (Value)); end Register; -- ------------------------------ -- Register the value under the given name. -- ------------------------------ procedure Register (Resolver : in out Default_ELResolver; Name : in Unbounded_String; Value : in EL.Objects.Object) is Key : constant String := To_String (Name); begin Objects.Maps.Include (Resolver.Map, Key, Value); end Register; overriding procedure Finalize (Obj : in out Default_Context) is begin if Obj.Var_Mapper_Created then Free (Obj.Var_Mapper); end if; end Finalize; end EL.Contexts.Default;
Update implementation to use the Object.Maps with a String as a key
Update implementation to use the Object.Maps with a String as a key
Ada
apache-2.0
stcarrez/ada-el
b749f120cd88cccae2b0d639b066c5d25eb734c9
src/gen-artifacts-docs-googlecode.ads
src/gen-artifacts-docs-googlecode.ads
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private package Gen.Artifacts.Docs.Googlecode is -- Format documentation for Google Wiki syntax. type Document_Formatter is new Gen.Artifacts.Docs.Document_Formatter with record Need_Newline : Boolean := False; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String; -- Start a new document. overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type); -- Write a line in the target document formatting the line if necessary. overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type); -- Finish the document. overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String); end Gen.Artifacts.Docs.Googlecode;
----------------------------------------------------------------------- -- gen-artifacts-docs-googlecode -- Artifact for Googlecode documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private package Gen.Artifacts.Docs.Googlecode is -- Format documentation for Google Wiki syntax. type Document_Formatter is new Gen.Artifacts.Docs.Document_Formatter with record Need_Newline : Boolean := False; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String; -- Start a new document. overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type); -- Write a line in the target document formatting the line if necessary. overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type); -- Finish the document. overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String); -- Write a line in the document. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in String); end Gen.Artifacts.Docs.Googlecode;
Declare the Write_Line procedure
Declare the Write_Line procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
7b22fe9a3a4b1f8452591edfc28d3dfba436c32d
regtests/util-streams-files-tests.adb
regtests/util-streams-files-tests.adb
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Files; with Util.Streams.Texts; package body Util.Streams.Files.Tests is use Util.Tests; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Files.Create, Write, Flush, Close", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Files.Write, Flush", Test_Write'Access); end Add_Tests; -- ------------------------------ -- Test reading and writing on a buffered stream with various buffer sizes -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : aliased File_Stream; Buffer : Util.Streams.Texts.Print_Stream; begin for I in 1 .. 32 loop Buffer.Initialize (Output => Stream'Unchecked_Access, Size => I); Stream.Create (Mode => Out_File, Name => "test-stream.txt"); Buffer.Write ("abcd"); Buffer.Write (" fghij"); Buffer.Flush; Stream.Close; declare Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => "test-stream.txt", Into => Content, Max_Size => 10000); Assert_Equals (T, "abcd fghij", Content, "Invalid content written to the file stream"); end; end loop; end Test_Read_Write; procedure Test_Write (T : in out Test) is begin null; end Test_Write; end Util.Streams.Files.Tests;
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2010, 2011, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Test_Caller; with Util.Files; with Util.Streams.Texts; package body Util.Streams.Files.Tests is use Util.Tests; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Files"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Files.Create, Write, Flush, Close", Test_Read_Write'Access); Caller.Add_Test (Suite, "Test Util.Streams.Files.Write, Flush", Test_Write'Access); end Add_Tests; -- ------------------------------ -- Test reading and writing on a buffered stream with various buffer sizes -- ------------------------------ procedure Test_Read_Write (T : in out Test) is Stream : aliased File_Stream; Buffer : Util.Streams.Texts.Print_Stream; begin for I in 1 .. 32 loop Buffer.Initialize (Output => Stream'Access, Size => I); Stream.Create (Mode => Out_File, Name => "test-stream.txt"); Buffer.Write ("abcd"); Buffer.Write (" fghij"); Buffer.Flush; Stream.Close; declare Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Files.Read_File (Path => "test-stream.txt", Into => Content, Max_Size => 10000); Assert_Equals (T, "abcd fghij", Content, "Invalid content written to the file stream"); end; end loop; end Test_Read_Write; procedure Test_Write (T : in out Test) is begin null; end Test_Write; end Util.Streams.Files.Tests;
Replace Unchecked_Access by Access in stream initialization
Replace Unchecked_Access by Access in stream initialization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bbcc4ed0602fcc1fe6f8835a23862aa0fa9c9285
regtests/util-streams-texts-tests.adb
regtests/util-streams-texts-tests.adb
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2012, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; package body Util.Streams.Texts.Tests is use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Texts"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close", Test_Read_Line'Access); end Add_Tests; -- ------------------------------ -- Test reading a text stream. -- ------------------------------ procedure Test_Read_Line (T : in out Test) is Stream : aliased Files.File_Stream; Reader : Util.Streams.Texts.Reader_Stream; Count : Natural := 0; begin Stream.Open (Name => "Makefile", Mode => In_File); Reader.Initialize (From => Stream'Access); while not Reader.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Reader.Read_Line (Line); Count := Count + 1; end; end loop; Stream.Close; T.Assert (Count > 100, "Too few lines read"); end Test_Read_Line; end Util.Streams.Texts.Tests;
----------------------------------------------------------------------- -- streams.files.tests -- Unit tests for buffered streams -- Copyright (C) 2012, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams.Stream_IO; with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; package body Util.Streams.Texts.Tests is use Ada.Streams.Stream_IO; use Util.Tests; package Caller is new Util.Test_Caller (Test, "Streams.Texts"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close", Test_Read_Line'Access); Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Integer)", Test_Write_Integer'Access); end Add_Tests; -- ------------------------------ -- Test reading a text stream. -- ------------------------------ procedure Test_Read_Line (T : in out Test) is Stream : aliased Files.File_Stream; Reader : Util.Streams.Texts.Reader_Stream; Count : Natural := 0; begin Stream.Open (Name => "Makefile", Mode => In_File); Reader.Initialize (From => Stream'Access); while not Reader.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; begin Reader.Read_Line (Line); Count := Count + 1; end; end loop; Stream.Close; T.Assert (Count > 100, "Too few lines read"); end Test_Read_Line; -- ------------------------------ -- Write on a text stream converting an integer and writing it. -- ------------------------------ procedure Test_Write_Integer (T : in out Test) is Stream : Print_Stream; Buf : Ada.Strings.Unbounded.Unbounded_String; begin Stream.Initialize (Size => 4); -- Write '0' (we don't want the Ada spurious space). Stream.Write (Integer (0)); Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '1234' Stream.Write (Integer (1234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "1234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); -- Write '-234' Stream.Write (Integer (-234)); Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream"); Stream.Flush (Buf); Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string"); Assert_Equals (T, "-234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content"); Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush"); end Test_Write_Integer; end Util.Streams.Texts.Tests;
Add Test_Write_Integer procedure and register it for execution
Add Test_Write_Integer procedure and register it for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9b1118959e88e1cf13c2e82fcc9f7afaa60680c5
src/util-measures.adb
src/util-measures.adb
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; with GNAT.Calendar.Time_IO; with Util.Streams.Buffered; package body Util.Measures is ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S"; procedure Free is new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access); procedure Free is new Ada.Unchecked_Deallocation (Measure, Measure_Access); procedure Free is new Ada.Unchecked_Deallocation (String, String_Access); package Task_Context is new Ada.Task_Attributes (Measure_Set_Access, null); function Format (D : in Duration) return String; -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. function Format (D : in Duration; Unit : in Unit_Type) return String; -- ------------------------------ -- Disable collecting measures on the measure set. -- ------------------------------ procedure Disable (Measures : in out Measure_Set) is begin Measures.Enabled := False; end Disable; -- ------------------------------ -- Enable collecting measures on the measure set. -- ------------------------------ procedure Enable (Measures : in out Measure_Set) is begin Measures.Enabled := True; end Enable; -- ------------------------------ -- Set the per-thread measure set. -- ------------------------------ procedure Set_Current (Measures : in Measure_Set_Access) is begin Task_Context.Set_Value (Measures); end Set_Current; -- ------------------------------ -- Get the per-thread measure set. -- ------------------------------ function Get_Current return Measure_Set_Access is begin return Task_Context.Value; end Get_Current; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class) is use Util.Streams.Buffered; procedure Dump_XML (Item : in Measure_Access); procedure Dump_XML (Item : in Measure_Access) is Total : constant String := Format (Item.Time); Time : constant String := Format (Item.Time / Item.Count); begin Stream.Write ("<time count="""); Stream.Write (Item.Count); Stream.Write (""" time="""); Stream.Write (Time (Time'First + 1 .. Time'Last)); if Item.Count > 1 then Stream.Write (""" total="""); Stream.Write (Total (Total'First + 1 .. Total'Last)); end if; Stream.Write (""" title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream), Content => Item.Name.all); Stream.Write ("""/>"); Stream.Write (ASCII.LF); end Dump_XML; Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin Measures.Data.Steal_Map (Buckets, TS, TE); Stream.Write ("<measures title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream), Content => Title); Stream.Write (""" start="""); Stream.Write (TS, ISO_DATE_TIME); Stream.Write (""" end="""); Stream.Write (TE, ISO_DATE_TIME); Stream.Write (""">"); if Buckets /= null then begin for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Dump_XML (Node); Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; exception when others => Free (Buckets); raise; end; Free (Buckets); end if; Stream.Write ("</measures>"); end Write; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type) is Buffer : aliased Util.Streams.Buffered.Buffered_Stream; Output : Util.Streams.Texts.Print_Stream; begin Buffer.Initialize (Size => 128 * 1024); Output.Initialize (To => Buffer'Unchecked_Access); Write (Measures, Title, Output); Output.Flush; Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer)); end Write; -- ------------------------------ -- Dump an XML result with the measures in a file. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => File, Name => Path); Write (Measures, Title, File); Ada.Text_IO.Close (File); exception when others => if Ada.Text_IO.Is_Open (File) then Ada.Text_IO.Close (File); end if; raise; end Write; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. -- ------------------------------ procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1) is Measures : constant Measure_Set_Access := Task_Context.Value; begin if Measures /= null and then Measures.Enabled then Report (Measures.all, S, Title, Count); end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. -- ------------------------------ procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1) is use Ada.Calendar; begin if Measures.Enabled then declare D : constant Duration := Ada.Calendar.Clock - S.Start; begin Measures.Data.Add (Title, D, Count); end; S.Start := Ada.Calendar.Clock; end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. -- ------------------------------ procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds) is use Ada.Calendar; D : constant Duration := Ada.Calendar.Clock - S.Start; begin Ada.Text_IO.Put (File, Title); Ada.Text_IO.Put (File, Format (D, Unit)); S.Start := Ada.Calendar.Clock; end Report; protected body Measure_Data is -- ------------------------------ -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. -- ------------------------------ procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time) is begin Result := Buckets; Time_Start := Start; Start := Ada.Calendar.Clock; Time_End := Start; Buckets := null; end Steal_Map; -- ------------------------------ -- Add the measure -- ------------------------------ procedure Add (Title : in String; D : in Duration; Count : in Positive := 1) is use Ada.Containers; use Ada.Calendar; Pos : Hash_Type; Node : Measure_Access; begin if Buckets = null then Buckets := new Buckets_Type (0 .. 256); end if; Pos := Ada.Strings.Hash (Title) mod Buckets'Length; Node := Buckets (Pos); while Node /= null loop if Node.Name'Length = Title'Length and then Node.Name.all = Title then Node.Count := Node.Count + Count; Node.Time := Node.Time + D; return; end if; Node := Node.Next; end loop; Buckets (Pos) := new Measure '(Name => new String '(Title), Time => D, Count => Count, Next => Buckets (Pos)); end Add; end Measure_Data; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration) return String is begin if D < 0.000_001 then return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns"; elsif D < 0.001 then return Duration'Image (D * 1_000_000) (1 .. 6) & " us"; elsif D < 1.0 then return Duration'Image (D * 1_000) (1 .. 6) & " ms"; else return Duration'Image (D) (1 .. 6) & " s"; end if; end Format; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration; Unit : in Unit_Type) return String is begin case Unit is when Seconds => return Duration'Image (D); when Milliseconds => return Duration'Image (D * 1_000); when Microseconds => return Duration'Image (D * 1_000_000); when Nanoseconds => return Duration'Image (D * 1_000_000_000); end case; end Format; -- ------------------------------ -- Finalize the measures and release the storage. -- ------------------------------ overriding procedure Finalize (Measures : in out Measure_Set) is Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin -- When deleting the measure set, we have to release the buckets and measures -- that were allocated. We could call <b>Write</b> but we don't know where -- the measures have to be written. Measures.Data.Steal_Map (Buckets, TS, TE); if Buckets /= null then for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; Free (Buckets); end if; end Finalize; end Util.Measures;
----------------------------------------------------------------------- -- measure -- Benchmark tools -- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Strings.Hash; with Ada.Unchecked_Deallocation; with GNAT.Calendar.Time_IO; with Util.Streams.Buffered; package body Util.Measures is ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S"; procedure Free is new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access); procedure Free is new Ada.Unchecked_Deallocation (Measure, Measure_Access); procedure Free is new Ada.Unchecked_Deallocation (String, String_Access); package Task_Context is new Ada.Task_Attributes (Measure_Set_Access, null); function Format (D : in Duration) return String; -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. function Format (D : in Duration; Unit : in Unit_Type) return String; -- ------------------------------ -- Disable collecting measures on the measure set. -- ------------------------------ procedure Disable (Measures : in out Measure_Set) is begin Measures.Enabled := False; end Disable; -- ------------------------------ -- Enable collecting measures on the measure set. -- ------------------------------ procedure Enable (Measures : in out Measure_Set) is begin Measures.Enabled := True; end Enable; -- ------------------------------ -- Set the per-thread measure set. -- ------------------------------ procedure Set_Current (Measures : in Measure_Set_Access) is begin Task_Context.Set_Value (Measures); end Set_Current; -- ------------------------------ -- Get the per-thread measure set. -- ------------------------------ function Get_Current return Measure_Set_Access is begin return Task_Context.Value; end Get_Current; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- When writing the measures, the measure set is cleared. It is safe -- to write measures while other measures are being collected. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in out Util.Streams.Texts.Print_Stream'Class) is use Util.Streams.Buffered; procedure Dump_XML (Item : in Measure_Access); procedure Dump_XML (Item : in Measure_Access) is Total : constant String := Format (Item.Time); Time : constant String := Format (Item.Time / Item.Count); begin Stream.Write ("<time count="""); Stream.Write (Item.Count); Stream.Write (""" time="""); Stream.Write (Time (Time'First + 1 .. Time'Last)); if Item.Count > 1 then Stream.Write (""" total="""); Stream.Write (Total (Total'First + 1 .. Total'Last)); end if; Stream.Write (""" title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream), Content => Item.Name.all); Stream.Write ("""/>"); Stream.Write (ASCII.LF); end Dump_XML; Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin Measures.Data.Steal_Map (Buckets, TS, TE); Stream.Write ("<measures title="""); Util.Streams.Texts.TR.Escape_Java_Script (Into => Buffered_Stream (Stream), Content => Title); Stream.Write (""" start="""); Stream.Write (TS, ISO_DATE_TIME); Stream.Write (""" end="""); Stream.Write (TE, ISO_DATE_TIME); Stream.Write (""">"); if Buckets /= null then begin for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Dump_XML (Node); Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; exception when others => Free (Buckets); raise; end; Free (Buckets); end if; Stream.Write ("</measures>"); end Write; -- ------------------------------ -- Dump an XML result with the measures collected by the measure set. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Stream : in Ada.Text_IO.File_Type) is Buffer : aliased Util.Streams.Buffered.Buffered_Stream; Output : Util.Streams.Texts.Print_Stream; begin Buffer.Initialize (Size => 128 * 1024); Output.Initialize (To => Buffer'Unchecked_Access); Write (Measures, Title, Output); Output.Flush; Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer)); end Write; -- ------------------------------ -- Dump an XML result with the measures in a file. -- ------------------------------ procedure Write (Measures : in out Measure_Set; Title : in String; Path : in String) is File : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => File, Name => Path); Write (Measures, Title, File); Ada.Text_IO.Close (File); exception when others => if Ada.Text_IO.Is_Open (File) then Ada.Text_IO.Close (File); end if; raise; end Write; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the per-thread measure set under the given measure -- title. -- ------------------------------ procedure Report (S : in out Stamp; Title : in String; Count : in Positive := 1) is Measures : constant Measure_Set_Access := Task_Context.Value; begin if Measures /= null and then Measures.Enabled then Report (Measures.all, S, Title, Count); end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- Collect the result in the measure set under the given measure title. -- ------------------------------ procedure Report (Measures : in out Measure_Set; S : in out Stamp; Title : in String; Count : in Positive := 1) is use Ada.Calendar; begin if Measures.Enabled then declare D : constant Duration := Ada.Calendar.Clock - S.Start; begin Measures.Data.Add (Title, D, Count); end; S.Start := Ada.Calendar.Clock; end if; end Report; -- ------------------------------ -- Report the time spent between the stamp creation and this method call. -- The report is written in the file with the given title. The duration is -- expressed in the unit defined in <tt>Unit</tt>. -- ------------------------------ procedure Report (S : in out Stamp; File : in out Ada.Text_IO.File_Type; Title : in String; Unit : in Unit_Type := Microseconds) is use Ada.Calendar; D : constant Duration := Ada.Calendar.Clock - S.Start; begin Ada.Text_IO.Put (File, Title); Ada.Text_IO.Put (File, Format (D, Unit)); S.Start := Ada.Calendar.Clock; end Report; protected body Measure_Data is -- ------------------------------ -- Get the measures and clear to start a new set of measures. -- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time. -- ------------------------------ procedure Steal_Map (Result : out Buckets_Access; Time_Start : out Ada.Calendar.Time; Time_End : out Ada.Calendar.Time) is begin Result := Buckets; Time_Start := Start; Start := Ada.Calendar.Clock; Time_End := Start; Buckets := null; end Steal_Map; -- ------------------------------ -- Add the measure -- ------------------------------ procedure Add (Title : in String; D : in Duration; Count : in Positive := 1) is use Ada.Containers; use Ada.Calendar; Pos : Hash_Type; Node : Measure_Access; begin if Buckets = null then Buckets := new Buckets_Type (0 .. 256); end if; Pos := Ada.Strings.Hash (Title) mod Buckets'Length; Node := Buckets (Pos); while Node /= null loop if Node.Name'Length = Title'Length and then Node.Name.all = Title then Node.Count := Node.Count + Count; Node.Time := Node.Time + D; return; end if; Node := Node.Next; end loop; Buckets (Pos) := new Measure '(Name => new String '(Title), Time => D, Count => Count, Next => Buckets (Pos)); end Add; end Measure_Data; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration) return String is begin if D < 0.000_001 then return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns"; elsif D < 0.001 then return Duration'Image (D * 1_000_000) (1 .. 6) & " us"; elsif D < 1.0 then return Duration'Image (D * 1_000) (1 .. 6) & " ms"; else return Duration'Image (D) (1 .. 6) & " s"; end if; end Format; -- ------------------------------ -- Format the duration in a time in 'ns', 'us', 'ms' or seconds. -- ------------------------------ function Format (D : in Duration; Unit : in Unit_Type) return String is begin case Unit is when Seconds => return Duration'Image (D); when Milliseconds => return Duration'Image (D * 1_000); when Microseconds => return Duration'Image (D * 1_000_000); when Nanoseconds => return Duration'Image (D * 1_000_000_000); end case; end Format; -- ------------------------------ -- Finalize the measures and release the storage. -- ------------------------------ overriding procedure Finalize (Measures : in out Measure_Set) is Buckets : Buckets_Access; TS, TE : Ada.Calendar.Time; begin -- When deleting the measure set, we have to release the buckets and measures -- that were allocated. We could call <b>Write</b> but we don't know where -- the measures have to be written. Measures.Data.Steal_Map (Buckets, TS, TE); if Buckets /= null then for I in Buckets'Range loop declare Next : Measure_Access; Node : Measure_Access := Buckets (I); begin while Node /= null loop Free (Node.Name); Next := Node.Next; Free (Node); Node := Next; end loop; end; end loop; Free (Buckets); end if; end Finalize; end Util.Measures;
Fix compilation style warning
Fix compilation style warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
98697fce4c22453d145836bbf1830a9e34efd343
src/asf-contexts-exceptions.adb
src/asf-contexts-exceptions.adb
----------------------------------------------------------------------- -- asf-contexts-exceptions -- Exception handlers in faces context -- Copyright (C) 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; package body ASF.Contexts.Exceptions is -- ------------------------------ -- Take action to handle the <b>Exception_Event</b> instances that have been queued by -- calls to <b>Application.Publish_Event</b>. -- -- This operation is called after each ASF phase by the life cycle manager. -- ------------------------------ procedure Handle (Handler : in out Exception_Handler) is pragma Unreferenced (Handler); use ASF.Applications; use type ASF.Contexts.Faces.Faces_Context_Access; function Get_Message (Event : in Events.Exceptions.Exception_Event'Class; Context : in ASF.Contexts.Faces.Faces_Context'Class) return ASF.Applications.Messages.Message; procedure Process (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Get a localized message for the exception -- ------------------------------ function Get_Message (Event : in Events.Exceptions.Exception_Event'Class; Context : in ASF.Contexts.Faces.Faces_Context'Class) return ASF.Applications.Messages.Message is Name : constant String := Event.Get_Exception_Name; Msg : constant String := Event.Get_Exception_Message; begin if Msg'Length = 0 then return Messages.Factory.Get_Message (Context => Context, Message_Id => EXCEPTION_MESSAGE_BASIC_ID, Param1 => Name); else return Messages.Factory.Get_Message (Context => Context, Message_Id => EXCEPTION_MESSAGE_EXTENDED_ID, Param1 => Name, Param2 => Msg); end if; end Get_Message; -- ------------------------------ -- Process each exception event and add a message in the faces context. -- ------------------------------ procedure Process (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Msg : constant Messages.Message := Get_Message (Event, Context); begin Context.Add_Message (Client_Id => "", Message => Msg); Remove := True; end Process; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return; end if; if Context.Get_Response_Completed then return; end if; Context.Iterate_Exception (Process'Access); end Handle; -- ------------------------------ -- Queue an exception event to the exception handler. The exception event will be -- processed at the end of the current ASF phase. -- ------------------------------ procedure Queue_Exception (Queue : in out Exception_Queue; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Queue.Unhandled_Events.Append (ASF.Events.Exceptions.Create_Exception_Event (Ex)); end Queue_Exception; -- ------------------------------ -- Clear the exception queue. -- ------------------------------ overriding procedure Finalize (Queue : in out Exception_Queue) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Exceptions.Exception_Event'Class, Name => ASF.Events.Exceptions.Exception_Event_Access); Len : Natural; begin loop Len := Natural (Queue.Unhandled_Events.Length); exit when Len = 0; declare Event : ASF.Events.Exceptions.Exception_Event_Access := Queue.Unhandled_Events.Element (Len); begin Free (Event); Queue.Unhandled_Events.Delete (Len); end; end loop; end Finalize; end ASF.Contexts.Exceptions;
----------------------------------------------------------------------- -- asf-contexts-exceptions -- Exception handlers in faces context -- Copyright (C) 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; package body ASF.Contexts.Exceptions is -- ------------------------------ -- Take action to handle the <b>Exception_Event</b> instances that have been queued by -- calls to <b>Application.Publish_Event</b>. -- -- This operation is called after each ASF phase by the life cycle manager. -- ------------------------------ procedure Handle (Handler : in out Exception_Handler) is pragma Unreferenced (Handler); use ASF.Applications; use type ASF.Contexts.Faces.Faces_Context_Access; function Get_Message (Event : in Events.Exceptions.Exception_Event'Class; Context : in ASF.Contexts.Faces.Faces_Context'Class) return ASF.Applications.Messages.Message; procedure Process (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Get a localized message for the exception -- ------------------------------ function Get_Message (Event : in Events.Exceptions.Exception_Event'Class; Context : in ASF.Contexts.Faces.Faces_Context'Class) return ASF.Applications.Messages.Message is Name : constant String := Event.Get_Exception_Name; Msg : constant String := Event.Get_Exception_Message; Pos : constant Util.Strings.Maps.Cursor := Handler.Mapping.Find (Name); begin if Util.Strings.Maps.Has_Element (Pos) then return Messages.Factory.Get_Message (Context => Context, Message_Id => Util.Strings.Maps.Element (Pos), Param1 => Msg); elsif Msg'Length = 0 then return Messages.Factory.Get_Message (Context => Context, Message_Id => EXCEPTION_MESSAGE_BASIC_ID, Param1 => Name); else return Messages.Factory.Get_Message (Context => Context, Message_Id => EXCEPTION_MESSAGE_EXTENDED_ID, Param1 => Name, Param2 => Msg); end if; end Get_Message; -- ------------------------------ -- Process each exception event and add a message in the faces context. -- ------------------------------ procedure Process (Event : in Events.Exceptions.Exception_Event'Class; Remove : out Boolean; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Msg : constant Messages.Message := Get_Message (Event, Context); begin Context.Add_Message (Client_Id => "", Message => Msg); Remove := True; end Process; Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return; end if; if Context.Get_Response_Completed then return; end if; Context.Iterate_Exception (Process'Access); end Handle; -- ------------------------------ -- Set the message id to be used when a given exception name is raised. -- ------------------------------ procedure Set_Message (Handler : in out Exception_Handler; Name : in String; Message_Id : in String) is begin Handler.Mapping.Insert (Name, Message_Id); end Set_Message; -- ------------------------------ -- Queue an exception event to the exception handler. The exception event will be -- processed at the end of the current ASF phase. -- ------------------------------ procedure Queue_Exception (Queue : in out Exception_Queue; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Queue.Unhandled_Events.Append (ASF.Events.Exceptions.Create_Exception_Event (Ex)); end Queue_Exception; -- ------------------------------ -- Clear the exception queue. -- ------------------------------ overriding procedure Finalize (Queue : in out Exception_Queue) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Exceptions.Exception_Event'Class, Name => ASF.Events.Exceptions.Exception_Event_Access); Len : Natural; begin loop Len := Natural (Queue.Unhandled_Events.Length); exit when Len = 0; declare Event : ASF.Events.Exceptions.Exception_Event_Access := Queue.Unhandled_Events.Element (Len); begin Free (Event); Queue.Unhandled_Events.Delete (Len); end; end loop; end Finalize; end ASF.Contexts.Exceptions;
Implement Set_Message procedure to register an exception/message mapping Use the mapping table to get a message to be used for a given exception
Implement Set_Message procedure to register an exception/message mapping Use the mapping table to get a message to be used for a given exception
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
38ca9d15c82ef4c69483399e307ec5edd3bdb6f2
awa/regtests/awa-commands-tests.adb
awa/regtests/awa-commands-tests.adb
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Test_Caller; with Util.Log.Loggers; package body AWA.Commands.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests"); package Caller is new Util.Test_Caller (Test, "Commands"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop", Test_Start_Stop'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (tables)", Test_List_Tables'Access); end Add_Tests; -- ------------------------------ -- Execute the command and get the output in a string. -- ------------------------------ procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0) is P : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; begin if Input'Length > 0 then Log.Info ("Execute: {0} < {1}", Command, Input); elsif Output'Length > 0 then Log.Info ("Execute: {0} > {1}", Command, Output); else Log.Info ("Execute: {0}", Command); end if; P.Set_Input_Stream (Input); P.Set_Output_Stream (Output); P.Open (Command, Util.Processes.READ_ALL); -- Write on the process input stream. Result := Ada.Strings.Unbounded.Null_Unbounded_String; Buffer.Initialize (P'Unchecked_Access, 8192); Buffer.Read (Result); P.Close; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result)); Log.Info ("Command result: {0}", Result); Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed"); end Execute; -- ------------------------------ -- Test start and stop command. -- ------------------------------ procedure Test_Start_Stop (T : in out Test) is task Start_Server is entry Start; entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String); end Start_Server; task body Start_Server is Output : Ada.Strings.Unbounded.Unbounded_String; begin accept Start do null; end Start; begin T.Execute ("bin/awa_command -c test-sqlite.properties start -m 26123", "", "", Output, 0); exception when others => Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *"); end; accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do Result := Output; end Wait; end Start_Server; Result : Ada.Strings.Unbounded.Unbounded_String; begin -- Launch the 'start' command in a separate task because the command will hang. Start_Server.Start; delay 5.0; -- Launch the 'stop' command, this should terminate the 'start' command. T.Execute ("bin/awa_command -c test-sqlite.properties stop -m 26123", "", "", Result, 0); -- Wait for the task result. Start_Server.Wait (Result); Util.Tests.Assert_Matches (T, "Starting...", Result, "AWA start command output"); end Test_Start_Stop; procedure Test_List_Tables (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -t", "", "", Result, 0); Util.Tests.Assert_Matches (T, "awa_audit *[0-9]+", Result, "Missing awa_audit"); Util.Tests.Assert_Matches (T, "awa_session *[0-9]+", Result, "Missing awa_session"); Util.Tests.Assert_Matches (T, "entity_type *[0-9]+", Result, "Missing entity_type"); Util.Tests.Assert_Matches (T, "awa_wiki_page *[0-9]+", Result, "Missing awa_wiki_page"); end Test_List_Tables; end AWA.Commands.Tests;
----------------------------------------------------------------------- -- awa-commands-tests -- Test the AWA.Commands -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Util.Processes; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Test_Caller; with Util.Log.Loggers; package body AWA.Commands.Tests is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests"); package Caller is new Util.Test_Caller (Test, "Commands"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop", Test_Start_Stop'Access); Caller.Add_Test (Suite, "Test AWA.Commands.List (tables)", Test_List_Tables'Access); end Add_Tests; -- ------------------------------ -- Execute the command and get the output in a string. -- ------------------------------ procedure Execute (T : in out Test; Command : in String; Input : in String; Output : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0) is P : aliased Util.Streams.Pipes.Pipe_Stream; Buffer : Util.Streams.Buffered.Input_Buffer_Stream; begin if Input'Length > 0 then Log.Info ("Execute: {0} < {1}", Command, Input); elsif Output'Length > 0 then Log.Info ("Execute: {0} > {1}", Command, Output); else Log.Info ("Execute: {0}", Command); end if; P.Set_Input_Stream (Input); P.Set_Output_Stream (Output); P.Open (Command, Util.Processes.READ_ALL); -- Write on the process input stream. Result := Ada.Strings.Unbounded.Null_Unbounded_String; Buffer.Initialize (P'Unchecked_Access, 8192); Buffer.Read (Result); P.Close; Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result)); Log.Info ("Command result: {0}", Result); Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed"); end Execute; -- ------------------------------ -- Test start and stop command. -- ------------------------------ procedure Test_Start_Stop (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); task Start_Server is entry Start; entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String); end Start_Server; task body Start_Server is Output : Ada.Strings.Unbounded.Unbounded_String; begin accept Start do null; end Start; begin T.Execute ("bin/awa_command -c " & Config & " start -m 26123", "", "", Output, 0); exception when others => Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *"); end; accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do Result := Output; end Wait; end Start_Server; Result : Ada.Strings.Unbounded.Unbounded_String; begin -- Launch the 'start' command in a separate task because the command will hang. Start_Server.Start; delay 5.0; -- Launch the 'stop' command, this should terminate the 'start' command. T.Execute ("bin/awa_command -c " & Config & " stop -m 26123", "", "", Result, 0); -- Wait for the task result. Start_Server.Wait (Result); Util.Tests.Assert_Matches (T, "Starting...", Result, "AWA start command output"); end Test_Start_Stop; procedure Test_List_Tables (T : in out Test) is Config : constant String := Util.Tests.Get_Parameter ("test_config_path"); Result : Ada.Strings.Unbounded.Unbounded_String; begin T.Execute ("bin/awa_command -c " & Config & " list -t", "", "", Result, 0); Util.Tests.Assert_Matches (T, "awa_audit *[0-9]+", Result, "Missing awa_audit"); Util.Tests.Assert_Matches (T, "awa_session *[0-9]+", Result, "Missing awa_session"); Util.Tests.Assert_Matches (T, "entity_type *[0-9]+", Result, "Missing entity_type"); Util.Tests.Assert_Matches (T, "awa_wiki_page *[0-9]+", Result, "Missing awa_wiki_page"); end Test_List_Tables; end AWA.Commands.Tests;
Fix the start/stop test to use the test configuration file
Fix the start/stop test to use the test configuration file
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9087cd415a611b07f8055071f70f5f63cca03dea
tests/nanomsg-test_pair.adb
tests/nanomsg-test_pair.adb
-- The MIT License (MIT) -- Copyright (c) 2015 Pavel Zhukov <[email protected]> -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. with Nanomsg.Domains; with Nanomsg.Pair; with Aunit.Assertions; with Nanomsg.Messages; package body Nanomsg.Test_Pair is procedure Run_Test (T : in out TC) is use Aunit.Assertions; Address : constant String := "tcp://127.0.0.1:5555"; Request : constant String := "Calculate : 2 + 2"; Reply : constant String := "Answer: 4"; Req_Send : Nanomsg.Messages.Message_T; Req_Rcv : Nanomsg.Messages.Message_T := Nanomsg.Messages.Empty_Message; Rep_Send : Nanomsg.Messages.Message_T; Rep_Rcv : Nanomsg.Messages.Message_T := Nanomsg.Messages.Empty_Message; begin Nanomsg.Messages.From_String (Req_Send, Request); Nanomsg.Messages.From_String (Rep_Send, Reply); Nanomsg.Socket.Init (T.Socket1, Nanomsg.Domains.Af_Sp, Nanomsg.Pair.Nn_PAIR); Nanomsg.Socket.Init (T.Socket2, Nanomsg.Domains.Af_Sp, Nanomsg.Pair.Nn_PAIR); Assert (Condition => not T.Socket1.Is_Null, Message => "Failed to initialize socket1"); Assert (Condition => not T.Socket2.Is_Null, Message => "Failed to initialize socket2"); Assert (Condition => T.Socket1.Get_Fd /= T.Socket2.Get_Fd, Message => "Descriptors collision!"); Nanomsg.Socket.Bind (T.Socket2, "tcp://*:5555"); Nanomsg.Socket.Connect (T.Socket1, Address); -- Pair is bi-directional communication -- Sendting few messages for I in 1 .. 10 loop T.Socket1.Send (Req_Send); T.Socket2.Receive (Req_Rcv); Assert (Condition => Req_Rcv.Text = Request, Message => "Request damaged in tranmission"); end loop; -- Sending messages in reverse direction for I in 1 .. 10 loop T.Socket2.Send (Rep_Send); T.Socket1.Receive (Rep_Rcv); Assert (Condition => Rep_Rcv.Text = Reply, Message => "Reply damaged in tranmission"); end loop; end Run_Test; function Name (T : TC) return Message_String is begin return Aunit.Format ("Test case name : Pair pattern test"); end Name; procedure Tear_Down (T : in out Tc) is begin if T.Socket1.Get_Fd >= 0 then T.Socket1.Close; end if; if T.Socket2.Get_Fd >= 0 then T.Socket2.Close; end if; end Tear_Down; end Nanomsg.Test_Pair;
-- The MIT License (MIT) -- Copyright (c) 2015 Pavel Zhukov <[email protected]> -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. with Nanomsg.Domains; with Nanomsg.Pair; with Aunit.Assertions; with Nanomsg.Messages; package body Nanomsg.Test_Pair is procedure Run_Test (T : in out TC) is use Aunit.Assertions; Address : constant String := "tcp://127.0.0.1:5555"; Request : constant String := "Calculate : 2 + 2"; Reply : constant String := "Answer: 4"; Req_Send : Nanomsg.Messages.Message_T; Req_Rcv : Nanomsg.Messages.Message_T := Nanomsg.Messages.Empty_Message; Rep_Send : Nanomsg.Messages.Message_T; Rep_Rcv : Nanomsg.Messages.Message_T := Nanomsg.Messages.Empty_Message; begin Nanomsg.Messages.From_String (Req_Send, Request); Nanomsg.Messages.From_String (Rep_Send, Reply); Nanomsg.Socket.Init (T.Socket1, Nanomsg.Domains.Af_Sp, Nanomsg.Pair.Nn_PAIR); Nanomsg.Socket.Init (T.Socket2, Nanomsg.Domains.Af_Sp, Nanomsg.Pair.Nn_PAIR); Assert (Condition => not T.Socket1.Is_Null, Message => "Failed to initialize socket1"); Assert (Condition => not T.Socket2.Is_Null, Message => "Failed to initialize socket2"); Assert (Condition => T.Socket1.Get_Fd /= T.Socket2.Get_Fd, Message => "Descriptors collision!"); Nanomsg.Socket.Bind (T.Socket2, "tcp://*:5555"); Nanomsg.Socket.Connect (T.Socket1, Address); Assert (Condition => T.Socket1.Is_Ready (To_Send => True, To_Receive => False), Message => "Socket 1 is not ready"); Assert (Condition => T.Socket2.Is_Ready (To_Send => True, To_Receive => False), Message => "Socket 2 is not ready"); -- Pair is bi-directional communication -- Sendting few messages for I in 1 .. 10 loop T.Socket1.Send (Req_Send); T.Socket2.Receive (Req_Rcv); Assert (Condition => Req_Rcv.Text = Request, Message => "Request damaged in tranmission"); end loop; -- Sending messages in reverse direction for I in 1 .. 10 loop T.Socket2.Send (Rep_Send); T.Socket1.Receive (Rep_Rcv); Assert (Condition => Rep_Rcv.Text = Reply, Message => "Reply damaged in tranmission"); end loop; end Run_Test; function Name (T : TC) return Message_String is begin return Aunit.Format ("Test case name : Pair pattern test"); end Name; procedure Tear_Down (T : in out Tc) is begin if T.Socket1.Get_Fd >= 0 then T.Socket1.Close; end if; if T.Socket2.Get_Fd >= 0 then T.Socket2.Close; end if; end Tear_Down; end Nanomsg.Test_Pair;
Add pair socket test
Add pair socket test
Ada
mit
landgraf/nanomsg-ada
b2e860a4f2fc371b389a6fdb9359e31badedb1f4
regtests/gen-integration-tests.ads
regtests/gen-integration-tests.ads
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014, 2016, 2017, 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.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test dynamo create-project command --lib. procedure Test_Create_Lib_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist with exclude support command. procedure Test_Dist_Exclude (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command (XMI Datatype). procedure Test_Generate_XMI_Datatype (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with serialization code. procedure Test_Generate_Zargo_Serialization (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
----------------------------------------------------------------------- -- gen-integration-tests -- Tests for integration -- Copyright (C) 2012, 2013, 2014, 2016, 2017, 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.Unbounded; with Util.Tests; package Gen.Integration.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Execute the command and get the output in a string. procedure Execute (T : in out Test; Command : in String; Result : out Ada.Strings.Unbounded.Unbounded_String; Status : in Natural := 0); -- Test dynamo create-project command. procedure Test_Create_Project (T : in out Test); -- Test dynamo create-project command --ado. procedure Test_Create_ADO_Project (T : in out Test); -- Test dynamo create-project command --gtk. procedure Test_Create_GTK_Project (T : in out Test); -- Test dynamo create-project command --lib. procedure Test_Create_Lib_Project (T : in out Test); -- Test project configure. procedure Test_Configure (T : in out Test); -- Test propset command. procedure Test_Change_Property (T : in out Test); -- Test add-module command. procedure Test_Add_Module (T : in out Test); -- Test add-model command. procedure Test_Add_Model (T : in out Test); -- Test add-module-operation command. procedure Test_Add_Module_Operation (T : in out Test); -- Test add-service command. procedure Test_Add_Service (T : in out Test); -- Test add-query command. procedure Test_Add_Query (T : in out Test); -- Test add-page command. procedure Test_Add_Page (T : in out Test); -- Test add-layout command. procedure Test_Add_Layout (T : in out Test); -- Test add-ajax-form command. procedure Test_Add_Ajax_Form (T : in out Test); -- Test generate command. procedure Test_Generate (T : in out Test); -- Test help command. procedure Test_Help (T : in out Test); -- Test dist command. procedure Test_Dist (T : in out Test); -- Test dist with exclude support command. procedure Test_Dist_Exclude (T : in out Test); -- Test dist command. procedure Test_Info (T : in out Test); -- Test build-doc command. procedure Test_Build_Doc (T : in out Test); -- Test build-doc command with -pandoc. procedure Test_Build_Pandoc (T : in out Test); -- Test generate command with Hibernate XML mapping files. procedure Test_Generate_Hibernate (T : in out Test); -- Test generate command (XMI enum). procedure Test_Generate_XMI_Enum (T : in out Test); -- Test generate command (XMI Ada Bean). procedure Test_Generate_XMI_Bean (T : in out Test); -- Test generate command (XMI Ada Bean with inheritance). procedure Test_Generate_XMI_Bean_Table (T : in out Test); -- Test generate command (XMI Ada Table). procedure Test_Generate_XMI_Table (T : in out Test); -- Test generate command (XMI Associations between Tables). procedure Test_Generate_XMI_Association (T : in out Test); -- Test generate command (XMI Datatype). procedure Test_Generate_XMI_Datatype (T : in out Test); -- Test generate command using the ArgoUML file directly (runs unzip -cq and parse the output). procedure Test_Generate_Zargo_Association (T : in out Test); -- Test UML with several tables that have dependencies between each of them (non circular). procedure Test_Generate_Zargo_Dependencies (T : in out Test); -- Test UML with several tables in several packages (non circular). procedure Test_Generate_Zargo_Packages (T : in out Test); -- Test UML with serialization code. procedure Test_Generate_Zargo_Serialization (T : in out Test); -- Test UML with several errors in the UML model. procedure Test_Generate_Zargo_Errors (T : in out Test); -- Test GNAT compilation of the final project. procedure Test_Build (T : in out Test); -- Test GNAT compilation of the generated model files. procedure Test_Build_Model (T : in out Test); end Gen.Integration.Tests;
Declare new test Test_Build_Pandoc
Declare new test Test_Build_Pandoc
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
d2df63aefc9638440ea7c72d7eb18cd78652a051
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 Ada.Unchecked_Deallocation; package body Security.Contexts is use type Security.Policies.Policy_Context_Array_Access; use type Security.Policies.Policy_Access; use type Security.Policies.Policy_Context_Access; package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context'Class, Name => Security.Policies.Policy_Context_Access); -- ------------------------------ -- 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; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return null; else return Context.Manager.Get_Policy (Name); end if; end Get_Policy; -- ------------------------------ -- 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.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare Perm : Security.Permissions.Permission (Permission); begin Result := Context.Manager.Has_Permission (Context, Perm); 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; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean) is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; Result := Context.Manager.Has_Permission (Context, Permission); 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 procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context_Array, Name => Security.Policies.Policy_Context_Array_Access); begin Task_Context.Set_Value (Context.Previous); if Context.Contexts /= null then for I in Context.Contexts'Range loop Free (Context.Contexts (I)); end loop; Free (Context.Contexts); end if; end Finalize; -- ------------------------------ -- Set a policy context information represented by <b>Value</b> and associated with -- the policy index <b>Policy</b>. -- ------------------------------ procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access) is begin if Context.Contexts = null then Context.Contexts := Context.Manager.Create_Policy_Contexts; end if; Free (Context.Contexts (Policy.Get_Policy_Index)); Context.Contexts (Policy.Get_Policy_Index) := Value; end Set_Policy_Context; -- ------------------------------ -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. -- ------------------------------ function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access is Result : Security.Policies.Policy_Context_Access; begin if Policy = null then raise Invalid_Policy; end if; if Context.Contexts = null then raise Invalid_Context; end if; Result := Context.Contexts (Policy.Get_Policy_Index); return Result; end Get_Policy_Context; -- ------------------------------ -- Returns True if a context information was registered for the security policy. -- ------------------------------ function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean is begin return Policy /= null and then Context.Contexts /= null and then Context.Contexts (Policy.Get_Policy_Index) /= null; end Has_Policy_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; with Ada.Unchecked_Deallocation; package body Security.Contexts is use type Security.Policies.Policy_Context_Array_Access; use type Security.Policies.Policy_Access; use type Security.Policies.Policy_Context_Access; package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context'Class, Name => Security.Policies.Policy_Context_Access); -- ------------------------------ -- 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; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return null; else return Context.Manager.Get_Policy (Name); end if; end Get_Policy; -- ------------------------------ -- 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.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare Perm : Security.Permissions.Permission (Permission); begin Result := Context.Manager.Has_Permission (Context, Perm); 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; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean) is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; Result := Context.Manager.Has_Permission (Context, Permission); 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 procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context_Array, Name => Security.Policies.Policy_Context_Array_Access); begin Task_Context.Set_Value (Context.Previous); if Context.Contexts /= null then for I in Context.Contexts'Range loop Free (Context.Contexts (I)); end loop; Free (Context.Contexts); end if; end Finalize; -- ------------------------------ -- Set a policy context information represented by <b>Value</b> and associated with -- the policy index <b>Policy</b>. -- ------------------------------ procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access) is begin if Context.Contexts = null then Context.Contexts := Context.Manager.Create_Policy_Contexts; end if; Free (Context.Contexts (Policy.Get_Policy_Index)); Context.Contexts (Policy.Get_Policy_Index) := Value; end Set_Policy_Context; -- ------------------------------ -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. -- ------------------------------ function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access is Result : Security.Policies.Policy_Context_Access; begin if Policy = null then raise Invalid_Policy; end if; if Context.Contexts = null then raise Invalid_Context; end if; Result := Context.Contexts (Policy.Get_Policy_Index); return Result; end Get_Policy_Context; -- ------------------------------ -- Returns True if a context information was registered for the security policy. -- ------------------------------ function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean is begin return Policy /= null and then Context.Contexts /= null and then Context.Contexts (Policy.Get_Policy_Index) /= null; end Has_Policy_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; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission'Class) 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;
Implement the Has_Permission function
Implement the Has_Permission function
Ada
apache-2.0
Letractively/ada-security
b2bd16734868a0f467c4b12c6a5b8e93f008b44c
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Log.Loggers; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); -- 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); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Set_Reader_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is begin null; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Log.Loggers; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; with Security.Permissions; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Positive'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); -- 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); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Set_Reader_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is begin null; end Finalize; end Security.Policies;
Implement the Add_Permission on Policy
Implement the Add_Permission on Policy
Ada
apache-2.0
Letractively/ada-security
b8aec95f3fcb408c8a049472f66f752d0f949db5
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Permissions.Permission_Index; begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; 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 Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access is use type Permissions.Permission_Index; begin if Index >= Manager.Last_Index then return null; else return Manager.Permissions (Index); end if; end Get_Controller; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Permissions.Permission_Index; begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
Remove the Get_Controller function
Remove the Get_Controller function
Ada
apache-2.0
stcarrez/ada-security
51bc9eeca5db0680615159b2789702b8466e8ea0
src/http/util-http-clients.adb
src/http/util-http-clients.adb
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Util.Http.Clients is -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Request : in Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Http.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients"); -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Request : in Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; if Http.Manager = null then Log.Error ("No HTTP manager was defined"); raise Program_Error with "No HTTP manager was defined."; end if; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
Add a log error and raise an exception if there is no http implementation selected
Add a log error and raise an exception if there is no http implementation selected
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
01a968adaa1d12e8d379e00f8fc46013665de6f9
src/asf-views-facelets.ads
src/asf-views-facelets.ads
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components; with Util.Strings; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String; -- Register the component factory bindings in the facelet factory. procedure Register (Factory : in out Facelet_Factory; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Register a module and directory where the module files are stored. procedure Register_Module (Factory : in out Facelet_Factory; Name : in String; Paths : in String); -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; Path : Unbounded_String; File : Util.Strings.String_Access; Modify_Time : Ada.Calendar.Time; end record; -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; -- Lock for accessing the shared cache protected type RW_Lock is entry Read; procedure Release_Read; entry Write; procedure Release_Write; private Readable : Boolean := True; Reader_Count : Natural := 0; end RW_Lock; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); Lock : RW_Lock; Map : Facelet_Maps.Map; Path_Map : Util.Strings.String_Map.Map; -- The component factory Factory : aliased ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
----------------------------------------------------------------------- -- asf-views-facelets -- Facelets representation and management -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Unbounded.Hash; with ASF.Views.Nodes; with ASF.Contexts.Facelets; with ASF.Factory; with ASF.Components; with Util.Strings; with Ada.Finalization; -- The <b>ASF.Views.Facelets</b> package contains the facelet factory -- responsible for getting the facelet tree from a facelet name. -- The facelets (or *.xhtml) files are loaded by the reader to form -- a tag node tree which is cached by the factory. The facelet factory -- is shared by multiple requests and threads. package ASF.Views.Facelets is type Facelet is private; type Facelet_Access is access all Facelet; -- Returns True if the facelet is null/empty. function Is_Null (F : Facelet) return Boolean; -- ------------------------------ -- Facelet factory -- ------------------------------ -- The facelet factory allows to retrieve the node tree to build the -- component tree. The node tree can be shared by several component trees. -- The node tree is initialized from the <b>XHTML</b> view file. It is put -- in a cache to avoid loading and parsing the file several times. type Facelet_Factory is limited private; -- Get the facelet identified by the given name. If the facelet is already -- loaded, the cached value is returned. The facelet file is searched in -- a set of directories configured in the facelet factory. procedure Find_Facelet (Factory : in out Facelet_Factory; Name : in String; Context : in ASF.Contexts.Facelets.Facelet_Context'Class; Result : out Facelet); -- Create the component tree from the facelet view. procedure Build_View (View : in Facelet; Context : in out ASF.Contexts.Facelets.Facelet_Context'Class; Root : in ASF.Components.UIComponent_Access); -- Initialize the facelet factory. -- Set the search directories for facelet files. -- Set the ignore white space configuration when reading XHTML files. -- Set the ignore empty lines configuration when reading XHTML files. -- Set the escape unknown tags configuration when reading XHTML files. procedure Initialize (Factory : in out Facelet_Factory; Paths : in String; Ignore_White_Spaces : in Boolean; Ignore_Empty_Lines : in Boolean; Escape_Unknown_Tags : in Boolean); -- Find the facelet file in one of the facelet directories. -- Returns the path to be used for reading the facelet file. function Find_Facelet_Path (Factory : Facelet_Factory; Name : String) return String; -- Register the component factory bindings in the facelet factory. procedure Register (Factory : in out Facelet_Factory; Bindings : in ASF.Factory.Factory_Bindings_Access); -- Register a module and directory where the module files are stored. procedure Register_Module (Factory : in out Facelet_Factory; Name : in String; Paths : in String); -- Clear the facelet cache procedure Clear_Cache (Factory : in out Facelet_Factory); private use Ada.Strings.Unbounded; type Facelet is record Root : ASF.Views.Nodes.Tag_Node_Access; Path : Unbounded_String; File : String_Access; Modify_Time : Ada.Calendar.Time; end record; -- Tag library map indexed on the library namespace. package Facelet_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Facelet, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); use Facelet_Maps; -- Lock for accessing the shared cache protected type RW_Lock is entry Read; procedure Release_Read; entry Write; procedure Release_Write; private Readable : Boolean := True; Reader_Count : Natural := 0; end RW_Lock; type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record Paths : Unbounded_String := To_Unbounded_String (""); Lock : RW_Lock; Map : Facelet_Maps.Map; Path_Map : Util.Strings.String_Map.Map; -- The component factory Factory : aliased ASF.Factory.Component_Factory; -- Whether the unknown tags are escaped using XML escape rules. Escape_Unknown_Tags : Boolean := True; -- Whether white spaces can be ignored. Ignore_White_Spaces : Boolean := True; -- Whether empty lines should be ignored (when white spaces are kept). Ignore_Empty_Lines : Boolean := True; end record; -- Free the storage held by the factory cache. overriding procedure Finalize (Factory : in out Facelet_Factory); end ASF.Views.Facelets;
Use Ada String_Access
Use Ada String_Access
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
39322a0294aa1e57aaffaba9906eec2b38889b2b
mat/src/gtk/gtkmatp.adb
mat/src/gtk/gtkmatp.adb
----------------------------------------------------------------------- -- gtkmatp -- Gtk MAT application -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Util.Log.Loggers; with Readline; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Callbacks; with Glib.Error; with Gtk.Main; with Gtk.Widget; with Gtkada.Builder; procedure GtkMatp is Builder : Gtkada.Builder.Gtkada_Builder; Error : aliased Glib.Error.GError; Result : Glib.Guint; Main : Gtk.Widget.Gtk_Widget; begin Gtk.Main.Init; Util.Log.Loggers.Initialize ("matp.properties"); Gtkada.Builder.Gtk_New (Builder); Result := Builder.Add_From_File ("mat.glade", Error'Access); Builder.Register_Handler (Handler_Name => "quit", Handler => MAT.Callbacks.On_Menu_Quit'Access); Builder.Register_Handler (Handler_Name => "about", Handler => MAT.Callbacks.On_Menu_About'Access); Builder.Register_Handler (Handler_Name => "close-about", Handler => MAT.Callbacks.On_Close_About'Access); Builder.Do_Connect; Main := Gtk.Widget.Gtk_Widget (Builder.Get_Object ("main")); Main.Show_All; Gtk.Main.Main; end GtkMatp;
----------------------------------------------------------------------- -- gtkmatp -- Gtk MAT application -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Util.Log.Loggers; with Readline; with MAT.Commands; with MAT.Targets; with MAT.Consoles.Text; with MAT.Callbacks; with Glib.Error; with Gtk.Main; with Gtk.Widget; with Gtkada.Builder; procedure GtkMatp is Builder : Gtkada.Builder.Gtkada_Builder; Error : aliased Glib.Error.GError; Result : Glib.Guint; Main : Gtk.Widget.Gtk_Widget; begin Gtk.Main.Init; Util.Log.Loggers.Initialize ("matp.properties"); Gtkada.Builder.Gtk_New (Builder); Result := Builder.Add_From_File ("mat.glade", Error'Access); Builder.Do_Connect; MAT.Callbacks.Initialize (Builder); Main := Gtk.Widget.Gtk_Widget (Builder.Get_Object ("main")); Main.Show_All; Gtk.Main.Main; end GtkMatp;
Use the MAT.Callbacks.Initialize operation to setup the gui
Use the MAT.Callbacks.Initialize operation to setup the gui
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fc9be187672d41d1f7e1aefb6ad29161b5d230f8
src/security-auth.ads
src/security-auth.ads
----------------------------------------------------------------------- -- security-auth -- Authentication Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == Auth == -- The <b>Security.Auth</b> package implements an authentication framework that is -- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application -- to authenticate users using an external authorization server such as Google, Facebook, -- Google +, Twitter and others. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- See OpenID Connect Standard 1.0 -- http://openid.net/specs/openid-connect-standard-1_0.html -- -- See Facebook API: The Login Flow for Web (without JavaScript SDK) -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- -- Despite their subtle differences, all these authentication frameworks share almost -- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable -- for all these frameworks. -- -- 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 Authentication manager must be declared and configured. -- -- Mgr : Security.Auth.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the Auth realm and set the authentication 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", -- Realm => "openid"); -- -- After this initialization, the authentication manager can be used in the authentication -- process. -- -- @include security-auth-openid.ads -- @include security-auth-oauth.ads -- -- === 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.Auth.End_Point; -- Assoc : constant Security.Auth.Association_Access := new Security.Auth.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. -- Credential : Security.Auth.Authentication; -- Params : Auth_Params; -- -- The auth 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, Credential); -- if Security.Auth.Get_Status (Credential) = Security.Auth.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.Auth.Principal_Access := Security.Auth.Create_Principal (Credential); -- package Security.Auth is -- Use an authentication server implementing OpenID 2.0. PROVIDER_OPENID : constant String := "openid"; -- Use the Facebook OAuth 2.0 - draft 12 authentication server. PROVIDER_FACEBOOK : constant String := "facebook"; Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- Auth provider -- ------------------------------ -- The <b>End_Point</b> represents the authentication provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The association contains the shared secret between the relying party -- and the authentication provider. The association can be cached and reused to authenticate -- different users using the same authentication provider. The association also has an -- expiration date. type Association is private; -- Get the provider. function Get_Provider (Assoc : in Association) return String; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- Authentication result -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- Authentication Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the authentication process. type Manager is tagged limited private; -- Initialize the authentication realm. procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); -- Discover the authentication 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. The discover step may do nothing for -- authentication providers based on OAuth. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the authentication provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); private use Ada.Strings.Unbounded; type Association is record Provider : Unbounded_String; Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager_Access is access all Manager'Class; type Manager is new Ada.Finalization.Limited_Controlled with record Provider : Unbounded_String; Delegate : Manager_Access; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String); end Security.Auth;
----------------------------------------------------------------------- -- security-auth -- Authentication Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == Auth == -- The <b>Security.Auth</b> package implements an authentication framework that is -- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application -- to authenticate users using an external authorization server such as Google, Facebook, -- Google +, Twitter and others. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- See OpenID Connect Standard 1.0 -- http://openid.net/specs/openid-connect-standard-1_0.html -- -- See Facebook API: The Login Flow for Web (without JavaScript SDK) -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- -- Despite their subtle differences, all these authentication frameworks share almost -- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable -- for all these frameworks. -- -- 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 Authentication manager must be declared and configured. -- -- Mgr : Security.Auth.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the Auth realm and set the authentication 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", -- Realm => "openid"); -- -- After this initialization, the authentication manager can be used in the authentication -- process. -- -- @include security-auth-openid.ads -- @include security-auth-oauth.ads -- -- === 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.Auth.End_Point; -- Assoc : constant Security.Auth.Association_Access := new Security.Auth.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. -- Credential : Security.Auth.Authentication; -- Params : Auth_Params; -- -- The auth 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, Credential); -- if Security.Auth.Get_Status (Credential) = Security.Auth.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.Auth.Principal_Access := Security.Auth.Create_Principal (Credential); -- package Security.Auth is -- Use an authentication server implementing OpenID 2.0. PROVIDER_OPENID : constant String := "openid"; -- Use the Facebook OAuth 2.0 - draft 12 authentication server. PROVIDER_FACEBOOK : constant String := "facebook"; -- Use the Google+ OpenID Connect Basic Client PROVIDER_GOOGLE_PLUS : constant String := "google-plus"; Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- Auth provider -- ------------------------------ -- The <b>End_Point</b> represents the authentication provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The association contains the shared secret between the relying party -- and the authentication provider. The association can be cached and reused to authenticate -- different users using the same authentication provider. The association also has an -- expiration date. type Association is private; -- Get the provider. function Get_Provider (Assoc : in Association) return String; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- Authentication result -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- Authentication Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the authentication process. type Manager is tagged limited private; -- Initialize the authentication realm. procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); -- Discover the authentication 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. The discover step may do nothing for -- authentication providers based on OAuth. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the authentication provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); private use Ada.Strings.Unbounded; type Association is record Provider : Unbounded_String; Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager_Access is access all Manager'Class; type Manager is new Ada.Finalization.Limited_Controlled with record Provider : Unbounded_String; Delegate : Manager_Access; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String); end Security.Auth;
Add Google+ provider
Add Google+ provider
Ada
apache-2.0
stcarrez/ada-security
2dddaaf30079cb5ef350a7711bd15901e46ae78f
src/wiki-documents.adb
src/wiki-documents.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; use Wiki.Nodes.Lists; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Parent => Into.Current, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0, Parent => Into.Current)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0, Parent => Into.Current)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0, Parent => Into.Current)); when N_LIST_ITEM => Append (Into, new Node_Type '(Kind => N_LIST_ITEM, Len => 0, Parent => Into.Current)); when N_LIST_END => Append (Into, new Node_Type '(Kind => N_LIST_END, Len => 0, Parent => Into.Current)); when N_NUM_LIST_END => Append (Into, new Node_Type '(Kind => N_NUM_LIST_END, Len => 0, Parent => Into.Current)); when N_LIST_ITEM_END => Append (Into, new Node_Type '(Kind => N_LIST_ITEM_END, Len => 0, Parent => Into.Current)); when N_NEWLINE => Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0, Parent => Into.Current)); when N_END_DEFINITION => Append (Into, new Node_Type '(Kind => N_END_DEFINITION, Len => 0, Parent => Into.Current)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0, Parent => Into.Current)); Into.Using_TOC := True; when N_NONE => null; end case; end Append; -- ------------------------------ -- Append the text with the given format at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Parent => Into.Current, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a definition item at end of the document. -- ------------------------------ procedure Add_Definition (Into : in out Document; Definition : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_DEFINITION, Len => Definition'Length, Parent => Into.Current, Header => Definition, Level => 0)); end Add_Definition; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list (<ul> or <ol>) starting at the given number. -- ------------------------------ procedure Add_List (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST_START, Len => 0, Parent => Into.Current, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST_START, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end if; end Add_List; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Into : in out Document; Level : in Natural) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end Add_Blockquote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Parent => Into.Current, Preformatted => Text, Language => Strings.To_UString (Format))); end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Into : in out Document) is Table : Node_Type_Access; Row : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; -- Create the current table. if Table = null then Table := new Node_Type '(Kind => N_TABLE, Len => 0, Tag_Start => TABLE_TAG, Children => null, Parent => Into.Current, others => <>); Append (Into, Table); end if; -- Add the row. Row := new Node_Type '(Kind => N_ROW, Len => 0, Tag_Start => TR_TAG, Children => null, Parent => Table, others => <>); Append (Table, Row); Into.Current := Row; end Add_Row; -- ------------------------------ -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. -- ------------------------------ procedure Add_Column (Into : in out Document; Attributes : in out Wiki.Attributes.Attribute_List) is Row : Node_Type_Access; Col : Node_Type_Access; begin -- Identify the current row. Row := Into.Current; while Row /= null and then Row.Kind /= N_ROW loop Row := Row.Parent; end loop; -- Add the new column. Col := new Node_Type '(Kind => N_COLUMN, Len => 0, Tag_Start => TD_TAG, Children => null, Parent => Row, Attributes => Attributes); Append (Row, Col); Into.Current := Col; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Into : in out Document) is Table : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; if Table /= null then Into.Current := Table.Parent; else Into.Current := null; end if; end Finish_Table; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Returns True if the table of contents is visible and must be rendered. -- ------------------------------ function Is_Visible_TOC (Doc : in Document) return Boolean is begin return Doc.Visible_TOC; end Is_Visible_TOC; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Lists.Node_List_Ref) is begin if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; use Wiki.Nodes.Lists; -- ------------------------------ -- Append a HTML tag start node to the document. -- ------------------------------ procedure Push_Node (Into : in out Document; Tag : in Html_Tag; Attributes : in Wiki.Attributes.Attribute_List) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Parent => Into.Current, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0, Parent => Into.Current)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0, Parent => Into.Current)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0, Parent => Into.Current)); when N_LIST_ITEM => Append (Into, new Node_Type '(Kind => N_LIST_ITEM, Len => 0, Parent => Into.Current)); when N_LIST_END => Append (Into, new Node_Type '(Kind => N_LIST_END, Len => 0, Parent => Into.Current)); when N_NUM_LIST_END => Append (Into, new Node_Type '(Kind => N_NUM_LIST_END, Len => 0, Parent => Into.Current)); when N_LIST_ITEM_END => Append (Into, new Node_Type '(Kind => N_LIST_ITEM_END, Len => 0, Parent => Into.Current)); when N_NEWLINE => Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0, Parent => Into.Current)); when N_END_DEFINITION => Append (Into, new Node_Type '(Kind => N_END_DEFINITION, Len => 0, Parent => Into.Current)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0, Parent => Into.Current)); Into.Using_TOC := True; when N_NONE => null; end case; end Append; -- ------------------------------ -- Append the text with the given format at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Format_Map) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Parent => Into.Current, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a definition item at end of the document. -- ------------------------------ procedure Add_Definition (Into : in out Document; Definition : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_DEFINITION, Len => Definition'Length, Parent => Into.Current, Header => Definition, Level => 0)); end Add_Definition; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list (<ul> or <ol>) starting at the given number. -- ------------------------------ procedure Add_List (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST_START, Len => 0, Parent => Into.Current, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST_START, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end if; end Add_List; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Into : in out Document; Level : in Natural) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end Add_Blockquote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Into : in out Document; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Parent => Into.Current, Preformatted => Text, Language => Strings.To_UString (Format))); end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Into : in out Document) is Table : Node_Type_Access; Row : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; -- Create the current table. if Table = null then Table := new Node_Type '(Kind => N_TABLE, Len => 0, Tag_Start => TABLE_TAG, Children => null, Parent => Into.Current, others => <>); Append (Into, Table); end if; -- Add the row. Row := new Node_Type '(Kind => N_ROW, Len => 0, Tag_Start => TR_TAG, Children => null, Parent => Table, others => <>); Append (Table, Row); Into.Current := Row; end Add_Row; -- ------------------------------ -- Add a column to the current table row. The column is configured with the -- given attributes. The column content is provided through calls to Append. -- ------------------------------ procedure Add_Column (Into : in out Document; Attributes : in out Wiki.Attributes.Attribute_List) is Row : Node_Type_Access; Col : Node_Type_Access; begin -- Identify the current row. Row := Into.Current; while Row /= null and then Row.Kind /= N_ROW loop Row := Row.Parent; end loop; -- Add the new column. Col := new Node_Type '(Kind => N_COLUMN, Len => 0, Tag_Start => TD_TAG, Children => null, Parent => Row, Attributes => Attributes); Append (Row, Col); Into.Current := Col; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Into : in out Document) is Table : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; if Table /= null then Into.Current := Table.Parent; else Into.Current := null; end if; end Finish_Table; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (Doc : in Document; Process : not null access procedure (Node : in Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Returns True if the table of contents is visible and must be rendered. -- ------------------------------ function Is_Visible_TOC (Doc : in Document) return Boolean is begin return Doc.Visible_TOC; end Is_Visible_TOC; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Lists.Node_List_Ref) is begin if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is begin return Doc.TOC; end Get_TOC; -- ------------------------------ -- Set a link definition. -- ------------------------------ procedure Set_Link (Doc : in out Document; Name : in Wiki.Strings.WString; Link : in Wiki.Strings.WString) is begin Doc.Links.Include (Name, Link); end Set_Link; -- ------------------------------ -- Get a link definition. -- ------------------------------ function Get_Link (Doc : in out Document; Name : in Wiki.Strings.WString) return Wiki.Strings.WString is Pos : constant Wiki.Strings.Maps.Cursor := Doc.Links.Find (Name); begin if Wiki.Strings.Maps.Has_Element (Pos) then return Wiki.Strings.Maps.Element (Pos); else return ""; end if; end Get_Link; end Wiki.Documents;
Implement Set_Link and Get_Link
Implement Set_Link and Get_Link
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d70f708953bc6ccb6c6b98e1bad5c88b29a90061
awa/src/awa-converters-dates.adb
awa/src/awa-converters-dates.adb
----------------------------------------------------------------------- -- awa-converters-dates -- Date Converters -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Exceptions; with Ada.Strings.Unbounded; with Util.Locales; with Util.Dates.Formats; with Util.Properties.Bundles; with Util.Beans.Objects.Time; with ASF.Locales; with ASF.Utils; with ASF.Applications.Main; package body AWA.Converters.Dates is ONE_HOUR : constant Duration := 3600.0; ONE_DAY : constant Duration := 24 * ONE_HOUR; -- ------------------------------ -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- ------------------------------ overriding function To_String (Convert : in Relative_Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in Util.Beans.Objects.Object) return String is Bundle : ASF.Locales.Bundle; Locale : constant Util.Locales.Locale := Context.Get_Locale; begin begin ASF.Applications.Main.Load_Bundle (Context.Get_Application.all, Name => "dates", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); exception when E : Util.Properties.Bundles.NO_BUNDLE => Component.Log_Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E)); end; -- Convert the value as a date here so that we can raise an Invalid_Conversion exception. declare use Ada.Calendar; Date : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value); Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Dt : constant Duration := Now - Date; Values : ASF.Utils.Object_Array (1 .. 1); Result : Ada.Strings.Unbounded.Unbounded_String; begin if Dt < 60.0 then return Bundle.Get ("date_moment_ago"); elsif Dt < 120.0 then return Bundle.Get ("date_minute_ago"); elsif Dt < ONE_HOUR then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / 60.0)); ASF.Utils.Formats.Format (Bundle.Get ("date_minutes_ago"), Values, Result); elsif Dt < 2 * ONE_HOUR then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / 60.0)); ASF.Utils.Formats.Format (Bundle.Get ("date_hour_ago"), Values, Result); elsif Dt < ONE_DAY then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_HOUR)); ASF.Utils.Formats.Format (Bundle.Get ("date_hours_ago"), Values, Result); elsif Dt < 2 * ONE_DAY then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_HOUR)); ASF.Utils.Formats.Format (Bundle.Get ("date_day_ago"), Values, Result); elsif Dt < 7 * ONE_DAY then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_DAY)); ASF.Utils.Formats.Format (Bundle.Get ("date_days_ago"), Values, Result); else declare use ASF.Converters.Dates; Pattern : constant String := Date_Converter'Class (Convert).Get_Pattern (Context, Component); begin return Util.Dates.Formats.Format (Pattern, Date, Bundle); end; end if; return Ada.Strings.Unbounded.To_String (Result); end; exception when E : others => raise ASF.Converters.Invalid_Conversion with Ada.Exceptions.Exception_Message (E); end To_String; end AWA.Converters.Dates;
----------------------------------------------------------------------- -- awa-converters-dates -- Date Converters -- Copyright (C) 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Exceptions; with Ada.Strings.Unbounded; with Util.Locales; with Util.Dates.Formats; with Util.Properties.Bundles; with Util.Beans.Objects.Time; with ASF.Locales; with ASF.Utils; with ASF.Applications.Main; package body AWA.Converters.Dates is ONE_HOUR : constant Duration := 3600.0; ONE_DAY : constant Duration := 24 * ONE_HOUR; -- ------------------------------ -- Convert the object value into a string. The object value is associated -- with the specified component. -- If the string cannot be converted, the Invalid_Conversion exception should be raised. -- ------------------------------ overriding function To_String (Convert : in Relative_Date_Converter; Context : in ASF.Contexts.Faces.Faces_Context'Class; Component : in ASF.Components.Base.UIComponent'Class; Value : in Util.Beans.Objects.Object) return String is Bundle : ASF.Locales.Bundle; Locale : constant Util.Locales.Locale := Context.Get_Locale; begin begin ASF.Applications.Main.Load_Bundle (Context.Get_Application.all, Name => "dates", Locale => Util.Locales.To_String (Locale), Bundle => Bundle); exception when E : Util.Properties.Bundles.NO_BUNDLE => Component.Log_Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E)); end; -- Convert the value as a date here so that we can raise an Invalid_Conversion exception. declare use Ada.Calendar; Date : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value); Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Dt : constant Duration := Now - Date; Values : ASF.Utils.Object_Array (1 .. 1); Result : Ada.Strings.Unbounded.Unbounded_String; begin if Dt < 60.0 then return Bundle.Get ("date_moment_ago"); elsif Dt < 120.0 then return Bundle.Get ("date_minute_ago"); elsif Dt < ONE_HOUR then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / 60.0)); ASF.Utils.Formats.Format (Bundle.Get ("date_minutes_ago"), Values, Result); elsif Dt < 2 * ONE_HOUR then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / 60.0)); ASF.Utils.Formats.Format (Bundle.Get ("date_hour_ago"), Values, Result); elsif Dt < ONE_DAY then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_HOUR)); ASF.Utils.Formats.Format (Bundle.Get ("date_hours_ago"), Values, Result); elsif Dt < 2 * ONE_DAY then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_HOUR)); ASF.Utils.Formats.Format (Bundle.Get ("date_day_ago"), Values, Result); elsif Dt < 7 * ONE_DAY then Values (1) := Util.Beans.Objects.To_Object (Natural (Dt / ONE_DAY)); ASF.Utils.Formats.Format (Bundle.Get ("date_days_ago"), Values, Result); else declare use ASF.Converters.Dates; Pattern : constant String := Date_Converter'Class (Convert).Get_Pattern (Context, Bundle, Component); begin return Util.Dates.Formats.Format (Pattern, Date, Bundle); end; end if; return Ada.Strings.Unbounded.To_String (Result); end; exception when E : others => raise ASF.Converters.Invalid_Conversion with Ada.Exceptions.Exception_Message (E); end To_String; end AWA.Converters.Dates;
Add the bundle to the Get_Pattern function call
Add the bundle to the Get_Pattern function call
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
07fe6f0e941f80d8f157c842fb31417db308411d
src/lumen-events-key_translate.adb
src/lumen-events-key_translate.adb
-- Lumen.Events.Key_Translate -- Translate X11 keysym to Lumen symbol -- -- Chip Richards, NiEstu, Phoenix AZ, Summer 2010 -- This code is covered by the ISC License: -- -- Copyright © 2010, NiEstu -- -- Permission to use, copy, modify, and/or 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. -- Environment with Ada.Characters.Latin_1; with Lumen.Events.Keys; use Lumen.Events.Keys; package body Lumen.Events.Key_Translate is -- Useful range boundaries and other markers Lo_Char : constant Key_Symbol := Key_Symbol (Character'Pos (Character'First)); Hi_Char : constant Key_Symbol := Key_Symbol (Character'Pos (Character'Last)); Lo_Graphic : constant Key_Symbol := Key_Symbol (Character'Pos (Ada.Characters.Latin_1.Space)); Lo_Spec_1 : constant Key_Symbol := 16#FF08#; -- X11 backspace Hi_Spec_1 : constant Key_Symbol := 16#FF1B#; -- X11 escape Lo_Spec_2 : constant Key_Symbol := Home; Hi_Spec_2 : constant Key_Symbol := KP_Equal; Lo_Mod : constant Key_Symbol := Shift_L; Hi_Mod : constant Key_Symbol := Hyper_R; Lo_Func : constant Key_Symbol := F1; Hi_Func : constant Key_Symbol := F35; Unknown_Symbol : constant Key_Symbol := Key_Symbol'Last; Self_Symbol : constant Key_Symbol := Key_Symbol'Last - 1; -- Translation array for specials that turn into Latin-1 control -- characters, or themselves type Translation_Target is record Val : Key_Symbol; Cat : Key_Category; end record; type Special_1_Translation is array (Lo_Spec_1 .. Hi_Spec_1) of Translation_Target; Specials_1 : Special_1_Translation := ( 16#FF08# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.BS)), Key_Control), 16#FF09# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.HT)), Key_Control), 16#FF0A# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.LF)), Key_Control), Clear => (Clear, Key_Special), 16#FF0D# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.CR)), Key_Control), Pause => (Pause, Key_Special), Scroll_Lock => (Scroll_Lock, Key_Special), Sys_Req => (Sys_Req, Key_Special), 16#FF1B# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.ESC)), Key_Control), others => (Unknown_Symbol, Key_Unknown) ); -- Translation array for specials that turn into themselves; needed because -- the ranges are discontinuous and have holes type Special_2_Translation is array (Lo_Spec_2 .. Hi_Spec_2) of Key_Symbol; Specials_2 : Special_2_Translation := ( Home => Self_Symbol, Left => Self_Symbol, Up => Self_Symbol, Right => Self_Symbol, Down => Self_Symbol, Page_Up => Self_Symbol, Page_Down => Self_Symbol, End_Key => Self_Symbol, Begin_Key => Self_Symbol, Select_Key => Self_Symbol, Print => Self_Symbol, Execute => Self_Symbol, Insert => Self_Symbol, Undo => Self_Symbol, Redo => Self_Symbol, Menu => Self_Symbol, Find => Self_Symbol, Cancel => Self_Symbol, Help => Self_Symbol, Break => Self_Symbol, Mode_Switch => Self_Symbol, Num_Lock => Self_Symbol, KP_Space => Self_Symbol, KP_Tab => Self_Symbol, KP_Enter => Self_Symbol, KP_F1 => Self_Symbol, KP_F2 => Self_Symbol, KP_F3 => Self_Symbol, KP_F4 => Self_Symbol, KP_Home => Self_Symbol, KP_Left => Self_Symbol, KP_Up => Self_Symbol, KP_Right => Self_Symbol, KP_Down => Self_Symbol, KP_Page_Up => Self_Symbol, KP_Page_Down => Self_Symbol, KP_End => Self_Symbol, KP_Begin => Self_Symbol, KP_Insert => Self_Symbol, KP_Delete => Self_Symbol, KP_Equal => Self_Symbol, KP_Multiply => Self_Symbol, KP_Add => Self_Symbol, KP_Separator => Self_Symbol, KP_Subtract => Self_Symbol, KP_Decimal => Self_Symbol, KP_Divide => Self_Symbol, KP_0 => Self_Symbol, KP_1 => Self_Symbol, KP_2 => Self_Symbol, KP_3 => Self_Symbol, KP_4 => Self_Symbol, KP_5 => Self_Symbol, KP_6 => Self_Symbol, KP_7 => Self_Symbol, KP_8 => Self_Symbol, KP_9 => Self_Symbol, others => Unknown_Symbol ); -- Translate an X11 keysym to a Lumen symbol and a category. The keysym -- comes in as a Key_Symbol type, but it's not really one just yet procedure Keysym_To_Symbol (Incoming : in Key_Symbol; Modifiers : in Modifier_Set; Outgoing : out Key_Symbol; Category : out Key_Category) is begin -- Keysym_To_Symbol -- Modifiers, like shift, ctrl, alt, etc. if Incoming in Lo_Mod .. Hi_Mod then Outgoing := Incoming; Category := Key_Modifier; -- Function keys elsif Incoming in Lo_Func .. Hi_Func then Outgoing := Incoming; Category := Key_Function; -- First group of specials; some actually get translated elsif Incoming in Lo_Spec_1 .. Hi_Spec_1 then if Specials_1 (Incoming).Val = Unknown_Symbol then Outgoing := Incoming; -- just retain its X11 value, whatever it means; maybe the user will know Category := Key_Unknown; else Outgoing := Specials_1 (Incoming).Val; Category := Specials_1 (Incoming).Cat; end if; -- Second group of specials, which all retain their values elsif Incoming in Lo_Spec_2 .. Hi_Spec_2 then Outgoing := Incoming; if Specials_2 (Incoming) = Unknown_Symbol then Category := Key_Unknown; else Category := Key_Special; end if; -- Finally, deal with straight Latin-1 characters; shouldn't get here -- because we catch them in Events, but just in case elsif Incoming in Lo_Char .. Hi_Char then Outgoing := Incoming; if Incoming < Lo_Graphic or Incoming = Character'Pos (Ada.Characters.Latin_1.DEL) then Category := Key_Control; else Category := Key_Graphic; end if; -- Any keysym that doesn't meet the above specifications else Outgoing := Incoming; Category := Key_Unknown; end if; end Keysym_To_Symbol; end Lumen.Events.Key_Translate;
-- Lumen.Events.Key_Translate -- Translate X11 keysym to Lumen symbol -- -- Chip Richards, NiEstu, Phoenix AZ, Summer 2010 -- This code is covered by the ISC License: -- -- Copyright © 2010, NiEstu -- -- Permission to use, copy, modify, and/or 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. -- Environment with Ada.Characters.Latin_1; with Lumen.Events.Keys; use Lumen.Events.Keys; package body Lumen.Events.Key_Translate is -- Useful range boundaries and other markers Lo_Char : constant Key_Symbol := Key_Symbol (Character'Pos (Character'First)); Hi_Char : constant Key_Symbol := Key_Symbol (Character'Pos (Character'Last)); Lo_Graphic : constant Key_Symbol := Key_Symbol (Character'Pos (Ada.Characters.Latin_1.Space)); Lo_Spec_1 : constant Key_Symbol := 16#FF08#; -- X11 backspace Hi_Spec_1 : constant Key_Symbol := 16#FF1B#; -- X11 escape Lo_Spec_2 : constant Key_Symbol := Home; Hi_Spec_2 : constant Key_Symbol := KP_Equal; Lo_Mod : constant Key_Symbol := Shift_L; Hi_Mod : constant Key_Symbol := Hyper_R; Lo_Func : constant Key_Symbol := F1; Hi_Func : constant Key_Symbol := F35; Unknown_Symbol : constant Key_Symbol := Key_Symbol'Last; Self_Symbol : constant Key_Symbol := Key_Symbol'Last - 1; -- Translation array for specials that turn into Latin-1 control -- characters, or themselves type Translation_Target is record Val : Key_Symbol; Cat : Key_Category; end record; type Special_1_Translation is array (Lo_Spec_1 .. Hi_Spec_1) of Translation_Target; Specials_1 : Special_1_Translation := ( 16#FF08# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.BS)), Key_Control), 16#FF09# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.HT)), Key_Control), 16#FF0A# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.LF)), Key_Control), Clear => (Clear, Key_Special), 16#FF0D# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.CR)), Key_Control), Pause => (Pause, Key_Special), Scroll_Lock => (Scroll_Lock, Key_Special), Sys_Req => (Sys_Req, Key_Special), 16#FF1B# => (Key_Symbol (Character'Pos (Ada.Characters.Latin_1.ESC)), Key_Control), others => (Unknown_Symbol, Key_Unknown) ); -- Translation array for specials that turn into themselves; needed because -- the ranges are discontinuous and have holes type Special_2_Translation is array (Lo_Spec_2 .. Hi_Spec_2) of Key_Symbol; Specials_2 : Special_2_Translation := ( Home => Self_Symbol, Left => Self_Symbol, Up => Self_Symbol, Right => Self_Symbol, Down => Self_Symbol, Page_Up => Self_Symbol, Page_Down => Self_Symbol, End_Key => Self_Symbol, Begin_Key => Self_Symbol, Select_Key => Self_Symbol, Print => Self_Symbol, Execute => Self_Symbol, Insert => Self_Symbol, Undo => Self_Symbol, Redo => Self_Symbol, Menu => Self_Symbol, Find => Self_Symbol, Cancel => Self_Symbol, Help => Self_Symbol, Break => Self_Symbol, Mode_Switch => Self_Symbol, Num_Lock => Self_Symbol, KP_Space => Self_Symbol, KP_Tab => Self_Symbol, KP_Enter => Self_Symbol, KP_F1 => Self_Symbol, KP_F2 => Self_Symbol, KP_F3 => Self_Symbol, KP_F4 => Self_Symbol, KP_Home => Self_Symbol, KP_Left => Self_Symbol, KP_Up => Self_Symbol, KP_Right => Self_Symbol, KP_Down => Self_Symbol, KP_Page_Up => Self_Symbol, KP_Page_Down => Self_Symbol, KP_End => Self_Symbol, KP_Begin => Self_Symbol, KP_Insert => Self_Symbol, KP_Delete => Self_Symbol, KP_Equal => Self_Symbol, KP_Multiply => Self_Symbol, KP_Add => Self_Symbol, KP_Separator => Self_Symbol, KP_Subtract => Self_Symbol, KP_Decimal => Self_Symbol, KP_Divide => Self_Symbol, KP_0 => Self_Symbol, KP_1 => Self_Symbol, KP_2 => Self_Symbol, KP_3 => Self_Symbol, KP_4 => Self_Symbol, KP_5 => Self_Symbol, KP_6 => Self_Symbol, KP_7 => Self_Symbol, KP_8 => Self_Symbol, KP_9 => Self_Symbol, others => Unknown_Symbol ); -- Translate an X11 keysym to a Lumen symbol and a category. The keysym -- comes in as a Key_Symbol type, but it's not really one just yet procedure Keysym_To_Symbol (Incoming : in Key_Symbol; Modifiers : in Modifier_Set; Outgoing : out Key_Symbol; Category : out Key_Category) is begin -- Keysym_To_Symbol -- Modifiers, like shift, ctrl, alt, etc. case Incoming is when Lo_Mod .. Hi_Mod => Outgoing := Incoming; Category := Key_Modifier; -- Function keys when Lo_Func .. Hi_Func => Outgoing := Incoming; Category := Key_Function; -- First group of specials; some actually get translated when Lo_Spec_1 .. Hi_Spec_1 => if Specials_1 (Incoming).Val = Unknown_Symbol then Outgoing := Incoming; -- just retain its X11 value, whatever it means; maybe the user will know Category := Key_Unknown; else Outgoing := Specials_1 (Incoming).Val; Category := Specials_1 (Incoming).Cat; end if; -- Second group of specials, which all retain their values when Lo_Spec_2 .. Hi_Spec_2 => Outgoing := Incoming; if Specials_2 (Incoming) = Unknown_Symbol then Category := Key_Unknown; else Category := Key_Special; end if; -- Finally, deal with straight Latin-1 characters; shouldn't get here -- because we catch them in Events, but just in case when Lo_Char .. Hi_Char => Outgoing := Incoming; if Incoming < Lo_Graphic or Incoming = Character'Pos (Ada.Characters.Latin_1.DEL) then Category := Key_Control; else Category := Key_Graphic; end if; -- Any keysym that doesn't meet the above specifications when others => Outgoing := Incoming; Category := Key_Unknown; end case; end Keysym_To_Symbol; end Lumen.Events.Key_Translate;
Replace series of if statements with case.
Events: Replace series of if statements with case. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/lumen2,darkestkhan/lumen
7b6562f006e58ac7416b69a16a89fe5630e32c14
src/util-beans-objects-readers.adb
src/util-beans-objects-readers.adb
----------------------------------------------------------------------- -- util-beans-objects-readers -- Datasets -- 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.Serialize.IO; package body Util.Beans.Objects.Readers is use type Maps.Map_Bean_Access; use type Vectors.Vector_Bean_Access; -- Start a document. overriding procedure Start_Document (Handler : in out Reader) is begin Object_Stack.Clear (Handler.Context); Object_Stack.Push (Handler.Context); Object_Stack.Current (Handler.Context).Map := new Maps.Map_Bean; end Start_Document; -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Reader; Name : in String) is Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); Next : Object_Context_Access; begin Object_Stack.Push (Handler.Context); Next := Object_Stack.Current (Handler.Context); Next.Map := new Maps.Map_Bean; if Current.Map /= null then Current.Map.Include (Name, To_Object (Next.List, DYNAMIC)); else Current.List.Append (To_Object (Next.List, DYNAMIC)); end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Reader; Name : in String) is begin Object_Stack.Pop (Handler.Context); end Finish_Object; overriding procedure Start_Array (Handler : in out Reader; Name : in String) is Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); Next : Object_Context_Access; begin Object_Stack.Push (Handler.Context); Next := Object_Stack.Current (Handler.Context); Next.List := new Vectors.Vector_Bean; if Current.Map /= null then Current.Map.Include (Name, To_Object (Next.List, DYNAMIC)); else Current.List.Append (To_Object (Next.List, DYNAMIC)); end if; end Start_Array; overriding procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural) is begin Object_Stack.Pop (Handler.Context); end Finish_Array; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); begin if Current.Map /= null then Current.Map.Set_Value (Name, Value); else Current.List.Append (Value); end if; end Set_Member; -- Report an error while parsing the input stream. The error message will be reported -- on the logger associated with the parser. The parser will be set as in error so that -- the <b>Has_Error</b> function will return True after parsing the whole file. procedure Error (Handler : in out Reader; Message : in String) is begin null; end Error; end Util.Beans.Objects.Readers;
----------------------------------------------------------------------- -- util-beans-objects-readers -- Datasets -- 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.Serialize.IO; package body Util.Beans.Objects.Readers is use type Maps.Map_Bean_Access; use type Vectors.Vector_Bean_Access; -- Start a document. overriding procedure Start_Document (Handler : in out Reader) is begin Object_Stack.Clear (Handler.Context); Object_Stack.Push (Handler.Context); Object_Stack.Current (Handler.Context).Map := new Maps.Map_Bean; end Start_Document; -- ----------------------- -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ----------------------- overriding procedure Start_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); Next : Object_Context_Access; begin Object_Stack.Push (Handler.Context); Next := Object_Stack.Current (Handler.Context); Next.Map := new Maps.Map_Bean; if Current.Map /= null then Current.Map.Include (Name, To_Object (Next.List, DYNAMIC)); else Current.List.Append (To_Object (Next.List, DYNAMIC)); end if; end Start_Object; -- ----------------------- -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ----------------------- overriding procedure Finish_Object (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is begin Object_Stack.Pop (Handler.Context); end Finish_Object; overriding procedure Start_Array (Handler : in out Reader; Name : in String; Logger : in out Util.Log.Logging'Class) is Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); Next : Object_Context_Access; begin Object_Stack.Push (Handler.Context); Next := Object_Stack.Current (Handler.Context); Next.List := new Vectors.Vector_Bean; if Current.Map /= null then Current.Map.Include (Name, To_Object (Next.List, DYNAMIC)); else Current.List.Append (To_Object (Next.List, DYNAMIC)); end if; end Start_Array; overriding procedure Finish_Array (Handler : in out Reader; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is begin Object_Stack.Pop (Handler.Context); end Finish_Array; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- overriding procedure Set_Member (Handler : in out Reader; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is pragma Unreferenced (Attribute); Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context); begin if Current.Map /= null then Current.Map.Set_Value (Name, Value); else Current.List.Append (Value); end if; end Set_Member; end Util.Beans.Objects.Readers;
Add a Logger parameter to the Reader operations Remove the Error procedure
Add a Logger parameter to the Reader operations Remove the Error procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
87d1131baccc4dcb20cc7e0a6f712821701bf09d
src/portscan-tests.adb
src/portscan-tests.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with File_Operations; with PortScan.Log; with Parameters; with Unix; with Ada.Characters.Latin_1; with Ada.Directories; with Ada.Exceptions; package body PortScan.Tests is package FOP renames File_Operations; package LOG renames PortScan.Log; package PM renames Parameters; package LAT renames Ada.Characters.Latin_1; package DIR renames Ada.Directories; package EX renames Ada.Exceptions; -------------------------------------------------------------------------------------------- -- exec_phase_check_plist -------------------------------------------------------------------------------------------- function exec_check_plist (specification : PSP.Portspecs; log_handle : TIO.File_Type; phase_name : String; seq_id : port_id; port_prefix : String; rootdir : String) return Boolean is passed_check : Boolean := True; namebase : constant String := specification.get_namebase; directory_list : entry_crate.Map; dossier_list : entry_crate.Map; begin LOG.log_phase_begin (log_handle, phase_name); TIO.Put_Line (log_handle, "====> Checking for package manifest issues"); if not ingest_manifests (specification => specification, log_handle => log_handle, directory_list => directory_list, dossier_list => dossier_list, seq_id => seq_id, namebase => namebase, port_prefix => port_prefix, rootdir => rootdir) then passed_check := False; end if; if orphaned_directories_detected (log_handle => log_handle, directory_list => directory_list, namebase => namebase, port_prefix => port_prefix, rootdir => rootdir) then passed_check := False; end if; if missing_directories_detected (log_handle, directory_list) then passed_check := False; end if; if orphaned_files_detected (log_handle => log_handle, dossier_list => dossier_list, namebase => namebase, port_prefix => port_prefix, rootdir => rootdir) then passed_check := False; end if; if missing_files_detected (log_handle, dossier_list) then passed_check := False; end if; if passed_check then TIO.Put_Line (log_handle, "====> No manifest issues found"); end if; LOG.log_phase_end (log_handle); return passed_check; end exec_check_plist; -------------------------------------------------------------------------------------------- -- ingest_manifests -------------------------------------------------------------------------------------------- function ingest_manifests (specification : PSP.Portspecs; log_handle : TIO.File_Type; directory_list : in out entry_crate.Map; dossier_list : in out entry_crate.Map; seq_id : port_id; namebase : String; port_prefix : String; rootdir : String) return Boolean is procedure eat_plist (position : subpackage_crate.Cursor); procedure insert_directory (directory : String; subpackage : HT.Text); result : Boolean := True; procedure insert_directory (directory : String; subpackage : HT.Text) is numsep : Natural := HT.count_char (directory, LAT.Solidus); canvas : HT.Text := HT.SUS (directory); begin for x in 1 .. numsep + 1 loop declare paint : String := HT.USS (canvas); my_new_rec : entry_record := (subpackage, False); begin if paint /= "" then if not directory_list.Contains (canvas) then directory_list.Insert (canvas, my_new_rec); end if; canvas := HT.SUS (HT.head (paint, "/")); end if; end; end loop; end insert_directory; procedure eat_plist (position : subpackage_crate.Cursor) is subpackage : HT.Text := subpackage_crate.Element (position).subpackage; manifest_file : String := "/construction/" & namebase & "/.manifest." & HT.USS (subpackage) & ".mktmp"; contents : String := FOP.get_file_contents (rootdir & manifest_file); identifier : constant String := HT.USS (subpackage) & " manifest: "; markers : HT.Line_Markers; begin HT.initialize_markers (contents, markers); loop exit when not HT.next_line_present (contents, markers); declare line : constant String := HT.extract_line (contents, markers); line_text : HT.Text := HT.SUS (line); new_rec : entry_record := (subpackage, False); begin if HT.leads (line, "@comment ") or else HT.leads (line, "@terminfo") or else HT.leads (line, "@rmtry ") or else HT.leads (line, "@postexec ") then null; elsif HT.leads (line, "@dir ") then declare dir : String := convert_to_absolute_path (port_prefix, HT.substring (line, 5, 0)); dir_text : HT.Text := HT.SUS (dir); excludeit : Boolean; begin if directory_list.Contains (dir_text) then -- There is one case where a redundant @dir symbol is desired: -- *) when a non-standard PREFIX is used. Pkg(8) needs to be given an -- explicit command to remove the package's root directory. excludeit := (LAT.Solidus & dir = port_prefix) and then (port_prefix /= HT.USS (PM.configuration.dir_localbase)); if not excludeit then result := False; declare spkg : String := HT.USS (directory_list.Element (dir_text).subpackage); begin if spkg /= "" then TIO.Put_Line (log_handle, "Redundant @dir symbol, " & identifier & dir & " will already be created by the " & spkg & " manifest"); else TIO.Put_Line (log_handle, "Redundant @dir symbol, " & identifier & dir & " will already be created by another manifest"); end if; end; end if; else insert_directory (dir, subpackage); end if; end; else declare modline : String := modify_file_if_necessary (port_prefix, line); ml_text : HT.Text := HT.SUS (modline); begin if dossier_list.Contains (ml_text) then result := False; declare spkg : String := HT.USS (dossier_list.Element (ml_text).subpackage); begin TIO.Put_Line (log_handle, "Duplicate file entry, " & identifier & modline & " already present in " & spkg & " manifest"); end; else dossier_list.Insert (ml_text, new_rec); declare plistdir : String := DIR.Containing_Directory (modline); begin insert_directory (plistdir, subpackage); end; end if; end; end if; end; end loop; exception when issue : others => TIO.Put_Line (log_handle, "check-plist error: " & EX.Exception_Message (issue)); end eat_plist; begin all_ports (seq_id).subpackages.Iterate (eat_plist'Access); return result; end ingest_manifests; -------------------------------------------------------------------------------------------- -- directory_excluded -------------------------------------------------------------------------------------------- function directory_excluded (port_prefix, candidate : String) return Boolean is -- mandatory candidate has ${STAGEDIR}/ stripped (no leading slash) localbase : constant String := HT.substring (port_prefix, 1, 0); lblen : constant Natural := localbase'Length; begin if candidate = localbase then return True; end if; declare shortcan : String := HT.substring (candidate, lblen + 1, 0); begin if shortcan = "bin" or else shortcan = "etc" or else shortcan = "etc/rc.d" or else shortcan = "include" or else shortcan = "lib" or else shortcan = "lib/pkgconfig" or else shortcan = "libdata" or else shortcan = "libexec" or else shortcan = "sbin" or else shortcan = "share" or else shortcan = "www" then return True; end if; if not HT.leads (shortcan, "share/") then return False; end if; end; declare shortcan : String := HT.substring (candidate, lblen + 7, 0); begin if shortcan = "doc" or else shortcan = "examples" or else shortcan = "info" or else shortcan = "locale" or else shortcan = "man" or else shortcan = "nls" then return True; end if; if shortcan'Length /= 8 or else not HT.leads (shortcan, "man/man") then return False; end if; case shortcan (shortcan'Last) is when '1' .. '9' | 'l' | 'n' => return True; when others => return False; end case; end; end directory_excluded; -------------------------------------------------------------------------------------------- -- orphaned_directories_detected -------------------------------------------------------------------------------------------- function orphaned_directories_detected (log_handle : TIO.File_Type; directory_list : in out entry_crate.Map; namebase : String; port_prefix : String; rootdir : String) return Boolean is localbase : constant String := HT.substring (port_prefix, 1, 0); stagedir : String := rootdir & "/construction/" & namebase & "/stage"; command : String := rootdir & "/usr/bin/find " & stagedir & " -type d -printf " & LAT.Quotation & "%P\n" & LAT.Quotation; status : Integer; comres : String := HT.USS (Unix.piped_command (command, status)); markers : HT.Line_Markers; lblen : constant Natural := localbase'Length; result : Boolean := False; errprefix : constant String := "Orphaned directory detected: "; begin if status /= 0 then TIO.Put_Line ("orphaned_directories_detected: command error: " & comres); return True; end if; HT.initialize_markers (comres, markers); loop exit when not HT.next_line_present (comres, markers); declare line : constant String := HT.extract_line (comres, markers); plist_dir : HT.Text := HT.SUS (line); begin if line /= "" then if directory_list.Contains (plist_dir) then directory_list.Update_Element (Position => directory_list.Find (plist_dir), Process => mark_verified'Access); else if not directory_excluded (port_prefix, line) then if HT.leads (line, localbase) then TIO.Put_Line (log_handle, errprefix & HT.substring (line, lblen + 1, 0)); else TIO.Put_Line (log_handle, errprefix & line); end if; result := True; end if; end if; end if; end; end loop; return result; end orphaned_directories_detected; -------------------------------------------------------------------------------------------- -- mark_verified -------------------------------------------------------------------------------------------- procedure mark_verified (key : HT.Text; Element : in out entry_record) is begin Element.verified := True; end mark_verified; -------------------------------------------------------------------------------------------- -- missing_directories_detected -------------------------------------------------------------------------------------------- function missing_directories_detected (log_handle : TIO.File_Type; directory_list : in out entry_crate.Map) return Boolean is procedure check (position : entry_crate.Cursor); result : Boolean := False; procedure check (position : entry_crate.Cursor) is rec : entry_record renames entry_crate.Element (position); plist_dir : String := HT.USS (entry_crate.Key (position)); begin if not rec.verified then TIO.Put_Line (log_handle, "Directory " & plist_dir & " listed on " & HT.USS (rec.subpackage) & " manifest is not present in the stage directory."); result := True; end if; end check; begin directory_list.Iterate (check'Access); return result; end missing_directories_detected; -------------------------------------------------------------------------------------------- -- missing_files_detected -------------------------------------------------------------------------------------------- function missing_files_detected (log_handle : TIO.File_Type; dossier_list : in out entry_crate.Map) return Boolean is procedure check (position : entry_crate.Cursor); result : Boolean := False; procedure check (position : entry_crate.Cursor) is rec : entry_record renames entry_crate.Element (position); plist_file : String := HT.USS (entry_crate.Key (position)); begin if not rec.verified then TIO.Put_Line (log_handle, "File " & plist_file & " listed on " & HT.USS (rec.subpackage) & " manifest is not present in the stage directory."); result := True; end if; end check; begin dossier_list.Iterate (check'Access); return result; end missing_files_detected; -------------------------------------------------------------------------------------------- -- orphaned_files_detected -------------------------------------------------------------------------------------------- function orphaned_files_detected (log_handle : TIO.File_Type; dossier_list : in out entry_crate.Map; namebase : String; port_prefix : String; rootdir : String) return Boolean is rawlbase : constant String := HT.USS (PM.configuration.dir_localbase); localbase : constant String := HT.substring (rawlbase, 1, 0); stagedir : String := rootdir & "/construction/" & namebase & "/stage"; command : String := rootdir & "/usr/bin/find " & stagedir & " \( -type f -o -type l \) -printf " & LAT.Quotation & "%P\n" & LAT.Quotation; status : Integer; comres : String := HT.USS (Unix.piped_command (command, status)); markers : HT.Line_Markers; lblen : constant Natural := localbase'Length; result : Boolean := False; errprefix : constant String := "Orphaned file detected: "; begin if status /= 0 then TIO.Put_Line ("orphaned_files_detected: command error: " & comres); return True; end if; HT.initialize_markers (comres, markers); loop exit when not HT.next_line_present (comres, markers); declare line : constant String := HT.extract_line (comres, markers); plist_file : HT.Text := HT.SUS (line); begin if not HT.IsBlank (plist_file) then if dossier_list.Contains (plist_file) then dossier_list.Update_Element (Position => dossier_list.Find (plist_file), Process => mark_verified'Access); else TIO.Put_Line (log_handle, errprefix & line); result := True; end if; end if; end; end loop; return result; end orphaned_files_detected; -------------------------------------------------------------------------------------------- -- modify_file_if_necessary -------------------------------------------------------------------------------------------- function modify_file_if_necessary (port_prefix, original : String) return String is begin if HT.leads (original, "@info ") then return convert_to_absolute_path (port_prefix, HT.substring (original, 6, 0)); elsif HT.leads (original, "@sample ") then return convert_to_absolute_path (port_prefix, HT.substring (original, 8, 0)); else return convert_to_absolute_path (port_prefix, original); end if; end modify_file_if_necessary; -------------------------------------------------------------------------------------------- -- convert_to_absolute_path -------------------------------------------------------------------------------------------- function convert_to_absolute_path (port_prefix, raw : String) return String is begin if raw'Length < 2 then return raw; end if; if raw (raw'First) = LAT.Solidus then return HT.substring (raw, 1, 0); end if; return HT.substring (port_prefix, 1, 0) & LAT.Solidus & raw; end convert_to_absolute_path; end PortScan.Tests;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with File_Operations; with PortScan.Log; with Parameters; with Unix; with Ada.Characters.Latin_1; with Ada.Directories; with Ada.Exceptions; package body PortScan.Tests is package FOP renames File_Operations; package LOG renames PortScan.Log; package PM renames Parameters; package LAT renames Ada.Characters.Latin_1; package DIR renames Ada.Directories; package EX renames Ada.Exceptions; -------------------------------------------------------------------------------------------- -- exec_phase_check_plist -------------------------------------------------------------------------------------------- function exec_check_plist (specification : PSP.Portspecs; log_handle : TIO.File_Type; phase_name : String; seq_id : port_id; port_prefix : String; rootdir : String) return Boolean is passed_check : Boolean := True; namebase : constant String := specification.get_namebase; directory_list : entry_crate.Map; dossier_list : entry_crate.Map; begin LOG.log_phase_begin (log_handle, phase_name); TIO.Put_Line (log_handle, "====> Checking for package manifest issues"); if not ingest_manifests (specification => specification, log_handle => log_handle, directory_list => directory_list, dossier_list => dossier_list, seq_id => seq_id, namebase => namebase, port_prefix => port_prefix, rootdir => rootdir) then passed_check := False; end if; if orphaned_directories_detected (log_handle => log_handle, directory_list => directory_list, namebase => namebase, port_prefix => port_prefix, rootdir => rootdir) then passed_check := False; end if; if missing_directories_detected (log_handle, directory_list) then passed_check := False; end if; if orphaned_files_detected (log_handle => log_handle, dossier_list => dossier_list, namebase => namebase, port_prefix => port_prefix, rootdir => rootdir) then passed_check := False; end if; if missing_files_detected (log_handle, dossier_list) then passed_check := False; end if; if passed_check then TIO.Put_Line (log_handle, "====> No manifest issues found"); end if; LOG.log_phase_end (log_handle); return passed_check; end exec_check_plist; -------------------------------------------------------------------------------------------- -- ingest_manifests -------------------------------------------------------------------------------------------- function ingest_manifests (specification : PSP.Portspecs; log_handle : TIO.File_Type; directory_list : in out entry_crate.Map; dossier_list : in out entry_crate.Map; seq_id : port_id; namebase : String; port_prefix : String; rootdir : String) return Boolean is procedure eat_plist (position : subpackage_crate.Cursor); procedure insert_directory (directory : String; subpackage : HT.Text); result : Boolean := True; procedure insert_directory (directory : String; subpackage : HT.Text) is numsep : Natural := HT.count_char (directory, LAT.Solidus); canvas : HT.Text := HT.SUS (directory); begin for x in 1 .. numsep + 1 loop declare paint : String := HT.USS (canvas); my_new_rec : entry_record := (subpackage, False); begin if paint /= "" then if not directory_list.Contains (canvas) then directory_list.Insert (canvas, my_new_rec); end if; canvas := HT.SUS (HT.head (paint, "/")); end if; end; end loop; end insert_directory; procedure eat_plist (position : subpackage_crate.Cursor) is subpackage : HT.Text := subpackage_crate.Element (position).subpackage; manifest_file : String := "/construction/" & namebase & "/.manifest." & HT.USS (subpackage) & ".mktmp"; contents : String := FOP.get_file_contents (rootdir & manifest_file); identifier : constant String := HT.USS (subpackage) & " manifest: "; markers : HT.Line_Markers; begin HT.initialize_markers (contents, markers); loop exit when not HT.next_line_present (contents, markers); declare line : constant String := HT.extract_line (contents, markers); line_text : HT.Text := HT.SUS (line); new_rec : entry_record := (subpackage, False); begin if HT.leads (line, "@comment ") or else HT.leads (line, "@terminfo") or else HT.leads (line, "@rmtry ") or else HT.leads (line, "@postexec ") then null; elsif HT.leads (line, "@dir ") then declare dir : String := convert_to_absolute_path (port_prefix, HT.substring (line, 5, 0)); dir_text : HT.Text := HT.SUS (dir); excludeit : Boolean; begin if directory_list.Contains (dir_text) then -- There is one case where a redundant @dir symbol is desired: -- *) when a non-standard PREFIX is used. Pkg(8) needs to be given an -- explicit command to remove the package's root directory. excludeit := (LAT.Solidus & dir = port_prefix) and then (port_prefix /= HT.USS (PM.configuration.dir_localbase)); if not excludeit then result := False; declare spkg : String := HT.USS (directory_list.Element (dir_text).subpackage); begin if spkg /= "" then TIO.Put_Line (log_handle, "Redundant @dir symbol, " & identifier & dir & " will already be created by the " & spkg & " manifest"); else TIO.Put_Line (log_handle, "Redundant @dir symbol, " & identifier & dir & " will already be created by another manifest"); end if; end; end if; else insert_directory (dir, subpackage); end if; end; else declare modline : String := modify_file_if_necessary (port_prefix, line); ml_text : HT.Text := HT.SUS (modline); begin if dossier_list.Contains (ml_text) then result := False; declare spkg : String := HT.USS (dossier_list.Element (ml_text).subpackage); begin TIO.Put_Line (log_handle, "Duplicate file entry, " & identifier & modline & " already present in " & spkg & " manifest"); end; else dossier_list.Insert (ml_text, new_rec); declare plistdir : String := DIR.Containing_Directory (modline); begin insert_directory (plistdir, subpackage); end; end if; end; end if; end; end loop; exception when issue : others => TIO.Put_Line (log_handle, "check-plist error: " & EX.Exception_Message (issue)); end eat_plist; begin all_ports (seq_id).subpackages.Iterate (eat_plist'Access); return result; end ingest_manifests; -------------------------------------------------------------------------------------------- -- directory_excluded -------------------------------------------------------------------------------------------- function directory_excluded (port_prefix, candidate : String) return Boolean is -- mandatory candidate has ${STAGEDIR}/ stripped (no leading slash) localbase : constant String := HT.substring (port_prefix, 1, 0); lblen : constant Natural := localbase'Length; begin if candidate = localbase then return True; end if; declare shortcan : String := HT.substring (candidate, lblen + 1, 0); begin if shortcan = "bin" or else shortcan = "etc" or else shortcan = "etc/rc.d" or else shortcan = "include" or else shortcan = "lib" or else shortcan = "lib/pkgconfig" or else shortcan = "libdata" or else shortcan = "libexec" or else shortcan = "sbin" or else shortcan = "share" or else shortcan = "www" then return True; end if; if not HT.leads (shortcan, "share/") then return False; end if; end; declare shortcan : String := HT.substring (candidate, lblen + 7, 0); begin if shortcan = "doc" or else shortcan = "examples" or else shortcan = "info" or else shortcan = "locale" or else shortcan = "man" or else shortcan = "nls" then return True; end if; if shortcan'Length /= 8 or else not HT.leads (shortcan, "man/man") then return False; end if; case shortcan (shortcan'Last) is when '1' .. '9' | 'l' | 'n' => return True; when others => return False; end case; end; end directory_excluded; -------------------------------------------------------------------------------------------- -- orphaned_directories_detected -------------------------------------------------------------------------------------------- function orphaned_directories_detected (log_handle : TIO.File_Type; directory_list : in out entry_crate.Map; namebase : String; port_prefix : String; rootdir : String) return Boolean is localbase : constant String := HT.substring (port_prefix, 1, 0); stagedir : String := rootdir & "/construction/" & namebase & "/stage"; command : String := rootdir & "/usr/bin/find " & stagedir & " -type d -printf " & LAT.Quotation & "%P\n" & LAT.Quotation; status : Integer; comres : String := HT.USS (Unix.piped_command (command, status)); markers : HT.Line_Markers; lblen : constant Natural := localbase'Length; result : Boolean := False; errprefix : constant String := "Orphaned directory detected: "; begin if status /= 0 then TIO.Put_Line ("orphaned_directories_detected: command error: " & comres); return True; end if; HT.initialize_markers (comres, markers); loop exit when not HT.next_line_present (comres, markers); declare line : constant String := HT.extract_line (comres, markers); plist_dir : HT.Text := HT.SUS (line); begin if line /= "" then if directory_list.Contains (plist_dir) then directory_list.Update_Element (Position => directory_list.Find (plist_dir), Process => mark_verified'Access); else if not directory_excluded (port_prefix, line) then if HT.leads (line, localbase) then TIO.Put_Line (log_handle, errprefix & HT.substring (line, lblen + 1, 0)); else TIO.Put_Line (log_handle, errprefix & line); end if; result := True; end if; end if; end if; end; end loop; return result; end orphaned_directories_detected; -------------------------------------------------------------------------------------------- -- mark_verified -------------------------------------------------------------------------------------------- procedure mark_verified (key : HT.Text; Element : in out entry_record) is begin Element.verified := True; end mark_verified; -------------------------------------------------------------------------------------------- -- missing_directories_detected -------------------------------------------------------------------------------------------- function missing_directories_detected (log_handle : TIO.File_Type; directory_list : in out entry_crate.Map) return Boolean is procedure check (position : entry_crate.Cursor); result : Boolean := False; procedure check (position : entry_crate.Cursor) is rec : entry_record renames entry_crate.Element (position); plist_dir : String := HT.USS (entry_crate.Key (position)); begin if not rec.verified then TIO.Put_Line (log_handle, "Directory " & plist_dir & " listed on " & HT.USS (rec.subpackage) & " manifest is not present in the stage directory."); result := True; end if; end check; begin directory_list.Iterate (check'Access); return result; end missing_directories_detected; -------------------------------------------------------------------------------------------- -- missing_files_detected -------------------------------------------------------------------------------------------- function missing_files_detected (log_handle : TIO.File_Type; dossier_list : in out entry_crate.Map) return Boolean is procedure check (position : entry_crate.Cursor); result : Boolean := False; procedure check (position : entry_crate.Cursor) is rec : entry_record renames entry_crate.Element (position); plist_file : String := HT.USS (entry_crate.Key (position)); begin if not rec.verified then TIO.Put_Line (log_handle, "File " & plist_file & " listed on " & HT.USS (rec.subpackage) & " manifest is not present in the stage directory."); result := True; end if; end check; begin dossier_list.Iterate (check'Access); return result; end missing_files_detected; -------------------------------------------------------------------------------------------- -- orphaned_files_detected -------------------------------------------------------------------------------------------- function orphaned_files_detected (log_handle : TIO.File_Type; dossier_list : in out entry_crate.Map; namebase : String; port_prefix : String; rootdir : String) return Boolean is rawlbase : constant String := HT.USS (PM.configuration.dir_localbase); localbase : constant String := HT.substring (rawlbase, 1, 0); stagedir : String := rootdir & "/construction/" & namebase & "/stage"; command : String := rootdir & "/usr/bin/find " & stagedir & " \( -type f -o -type l \) -printf " & LAT.Quotation & "%P\n" & LAT.Quotation; status : Integer; comres : String := HT.USS (Unix.piped_command (command, status)); markers : HT.Line_Markers; lblen : constant Natural := localbase'Length; result : Boolean := False; errprefix : constant String := "Orphaned file detected: "; begin if status /= 0 then TIO.Put_Line ("orphaned_files_detected: command error: " & comres); return True; end if; HT.initialize_markers (comres, markers); loop exit when not HT.next_line_present (comres, markers); declare line : constant String := HT.extract_line (comres, markers); plist_file : HT.Text := HT.SUS (line); begin if not HT.IsBlank (plist_file) then if dossier_list.Contains (plist_file) then dossier_list.Update_Element (Position => dossier_list.Find (plist_file), Process => mark_verified'Access); else if HT.leads (line, localbase) then TIO.Put_Line (log_handle, errprefix & HT.substring (line, lblen + 1, 0)); else TIO.Put_Line (log_handle, errprefix & line); end if; result := True; end if; end if; end; end loop; return result; end orphaned_files_detected; -------------------------------------------------------------------------------------------- -- modify_file_if_necessary -------------------------------------------------------------------------------------------- function modify_file_if_necessary (port_prefix, original : String) return String is begin if HT.leads (original, "@info ") then return convert_to_absolute_path (port_prefix, HT.substring (original, 6, 0)); elsif HT.leads (original, "@sample ") then return convert_to_absolute_path (port_prefix, HT.substring (original, 8, 0)); else return convert_to_absolute_path (port_prefix, original); end if; end modify_file_if_necessary; -------------------------------------------------------------------------------------------- -- convert_to_absolute_path -------------------------------------------------------------------------------------------- function convert_to_absolute_path (port_prefix, raw : String) return String is begin if raw'Length < 2 then return raw; end if; if raw (raw'First) = LAT.Solidus then return HT.substring (raw, 1, 0); end if; return HT.substring (port_prefix, 1, 0) & LAT.Solidus & raw; end convert_to_absolute_path; end PortScan.Tests;
Make orphaned file message match orphaned directory message
Make orphaned file message match orphaned directory message
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
c7f78f4c9775e2e048144e4d566b8624240234d0
matp/src/events/mat-events-timelines.ads
matp/src/events/mat-events-timelines.ads
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with MAT.Events.Targets; package MAT.Events.Timelines is -- Describe a section of the timeline. The section has a starting and ending -- event that marks the boundary of the section within the collected events. -- The timeline section gives the duration and some statistics about memory -- allocation made in the section. type Timeline_Info is record Start_Id : MAT.Events.Targets.Event_Id_Type := 0; Start_Time : MAT.Types.Target_Tick_Ref := 0; End_Id : MAT.Events.Targets.Event_Id_Type := 0; End_Time : MAT.Types.Target_Tick_Ref := 0; Duration : MAT.Types.Target_Time := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; end record; package Timeline_Info_Vectors is new Ada.Containers.Vectors (Positive, Timeline_Info); subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector; subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor; procedure Extract (Target : in out MAT.Events.Targets.Target_Events; Into : in out Timeline_Info_Vector); -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Targets.Probe_Event_Type; Max : in Positive; List : in out MAT.Events.Targets.Target_Event_Vector); end MAT.Events.Timelines;
----------------------------------------------------------------------- -- mat-events-timelines - Timelines -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with MAT.Expressions; with MAT.Events.Targets; package MAT.Events.Timelines is -- Describe a section of the timeline. The section has a starting and ending -- event that marks the boundary of the section within the collected events. -- The timeline section gives the duration and some statistics about memory -- allocation made in the section. type Timeline_Info is record Start_Id : MAT.Events.Targets.Event_Id_Type := 0; Start_Time : MAT.Types.Target_Tick_Ref := 0; End_Id : MAT.Events.Targets.Event_Id_Type := 0; End_Time : MAT.Types.Target_Tick_Ref := 0; Duration : MAT.Types.Target_Time := 0; Malloc_Count : Natural := 0; Realloc_Count : Natural := 0; Free_Count : Natural := 0; end record; package Timeline_Info_Vectors is new Ada.Containers.Vectors (Positive, Timeline_Info); subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector; subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor; procedure Extract (Target : in out MAT.Events.Targets.Target_Events; Into : in out Timeline_Info_Vector); -- Find in the events stream the events which are associated with a given event. -- When the <tt>Event</tt> is a memory allocation, find the associated reallocation -- and free events. When the event is a free, find the associated allocations. -- Collect at most <tt>Max</tt> events. procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class; Event : in MAT.Events.Targets.Probe_Event_Type; Max : in Positive; List : in out MAT.Events.Targets.Target_Event_Vector); -- Find the sizes of malloc and realloc events which is selected by the given filter. -- Update the <tt>Sizes</tt> map to keep track of the first event and last event and -- the number of events found for the corresponding size. procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class; Filter : in MAT.Expressions.Expression_Type; Sizes : in out MAT.Events.Targets.Size_Event_Info_Map); end MAT.Events.Timelines;
Declare the Find_Sizes operation to gather the sizes of malloc/realloc events
Declare the Find_Sizes operation to gather the sizes of malloc/realloc events
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0e40d44a85d8c876ac0c0a16f315f0f5d5eebb12
src/natools-web-comment_cookies.ads
src/natools-web-comment_cookies.ads
------------------------------------------------------------------------------ -- Copyright (c) 2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Comment_Cookies provides an object to store persitent -- -- information for comment forms. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Lockable; private with Natools.Constant_Indefinite_Ordered_Maps; package Natools.Web.Comment_Cookies is pragma Preelaborate; Cookie_Name : constant String := "c_info"; type Comment_Info is private; Null_Info : constant Comment_Info; function Create (Name : in S_Expressions.Atom_Refs.Immutable_Reference; Mail : in S_Expressions.Atom_Refs.Immutable_Reference; Link : in S_Expressions.Atom_Refs.Immutable_Reference; Filter : in S_Expressions.Atom_Refs.Immutable_Reference) return Comment_Info; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Comment_Info; function Name (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference; function Mail (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference; function Link (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference; function Filter (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference; function Named_Serialization (Info : in Comment_Info) return S_Expressions.Atom; function Positional_Serialization (Info : in Comment_Info) return S_Expressions.Atom; type Serialization_Kind is (Named, Positional); type Encoder is access function (Data : in S_Expressions.Atom) return String; type Decoder is access function (Data : in String) return S_Expressions.Atom; type Codec_DB is private; procedure Register (DB : in out Codec_DB; Key : in Character; Filter : in not null Decoder); procedure Set_Encoder (DB : in out Codec_DB; Filter : in not null Encoder; Serialization : in Serialization_Kind); function Encode (DB : in Codec_DB; Info : in Comment_Info) return String; function Decode (DB : in Codec_DB; Cookie : in String) return Comment_Info; private type Atom_Kind is (Name, Mail, Link, Filter); type Ref_Array is array (Atom_Kind) of S_Expressions.Atom_Refs.Immutable_Reference; type Comment_Info is record Refs : Ref_Array; end record; package Decoder_Maps is new Constant_Indefinite_Ordered_Maps (Character, Decoder); type Codec_DB is record Enc : Encoder := null; Dec : Decoder_Maps.Constant_Map; Serialization : Serialization_Kind := Named; end record; function Name (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference is (Info.Refs (Name)); function Mail (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference is (Info.Refs (Mail)); function Link (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference is (Info.Refs (Link)); function Filter (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference is (Info.Refs (Filter)); Null_Info : constant Comment_Info := (Refs => (others => S_Expressions.Atom_Refs.Null_Immutable_Reference)); end Natools.Web.Comment_Cookies;
------------------------------------------------------------------------------ -- Copyright (c) 2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Comment_Cookies provides an object to store persitent -- -- information for comment forms. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Refs; with Natools.S_Expressions.Lockable; private with Natools.Constant_Indefinite_Ordered_Maps; package Natools.Web.Comment_Cookies is pragma Preelaborate; Cookie_Name : constant String := "c_info"; type Comment_Info is private; Null_Info : constant Comment_Info; function Create (Name : in S_Expressions.Atom_Refs.Immutable_Reference; Mail : in S_Expressions.Atom_Refs.Immutable_Reference; Link : in S_Expressions.Atom_Refs.Immutable_Reference; Filter : in S_Expressions.Atom_Refs.Immutable_Reference) return Comment_Info; function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class) return Comment_Info; function Name (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference; function Mail (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference; function Link (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference; function Filter (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference; function Named_Serialization (Info : in Comment_Info) return S_Expressions.Atom; function Positional_Serialization (Info : in Comment_Info) return S_Expressions.Atom; type Serialization_Kind is (Named, Positional); type Encoder is access function (Data : in S_Expressions.Atom) return String; type Decoder is access function (Data : in String) return S_Expressions.Atom; type Codec_DB is private; procedure Register (DB : in out Codec_DB; Key : in Character; Filter : in not null Decoder); procedure Set_Encoder (DB : in out Codec_DB; Filter : in not null Encoder; Serialization : in Serialization_Kind); function Encode (DB : in Codec_DB; Info : in Comment_Info) return String; function Decode (DB : in Codec_DB; Cookie : in String) return Comment_Info; private type Atom_Kind is (Filter, Name, Mail, Link); type Ref_Array is array (Atom_Kind) of S_Expressions.Atom_Refs.Immutable_Reference; type Comment_Info is record Refs : Ref_Array; end record; package Decoder_Maps is new Constant_Indefinite_Ordered_Maps (Character, Decoder); type Codec_DB is record Enc : Encoder := null; Dec : Decoder_Maps.Constant_Map; Serialization : Serialization_Kind := Named; end record; function Name (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference is (Info.Refs (Name)); function Mail (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference is (Info.Refs (Mail)); function Link (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference is (Info.Refs (Link)); function Filter (Info : in Comment_Info) return S_Expressions.Atom_Refs.Immutable_Reference is (Info.Refs (Filter)); Null_Info : constant Comment_Info := (Refs => (others => S_Expressions.Atom_Refs.Null_Immutable_Reference)); end Natools.Web.Comment_Cookies;
improve storage order of atoms
comment_cookies: improve storage order of atoms
Ada
isc
faelys/natools-web,faelys/natools-web
6d26259fcf6933badfa2a95a3cacbbe4c4135f71
tests/nanomsg-test_message_send_receive_million.adb
tests/nanomsg-test_message_send_receive_million.adb
-- The MIT License (MIT) -- Copyright (c) 2015 Pavel Zhukov <[email protected]> -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. with Ada.Calendar; with Ada.Text_Io; with Nanomsg.Domains; with Nanomsg.Pipeline; with Aunit.Assertions; with Nanomsg.Messages; package body Nanomsg.Test_Message_Send_Receive_Million is procedure Run_Test (T : in out TC) is use Aunit.Assertions; Address : constant String := "tcp://127.0.0.1:5555"; Msg1 : Nanomsg.Messages.Message_T; Msg2 : Nanomsg.Messages.Message_T := Nanomsg.Messages.Empty_Message; Begun : Ada.Calendar.Time; use type Ada.Calendar.Time; Dur : Duration; begin Nanomsg.Messages.From_String (Msg1, "Hello world"); Nanomsg.Socket.Init (T.Socket1, Nanomsg.Domains.Af_Sp, Nanomsg.Pipeline.Nn_Push); Nanomsg.Socket.Init (T.Socket2, Nanomsg.Domains.Af_Sp, Nanomsg.Pipeline.Nn_Pull); Assert (Condition => not T.Socket1.Is_Null, Message => "Failed to initialize socket1"); Assert (Condition => not T.Socket2.Is_Null, Message => "Failed to initialize socket2"); Assert (Condition => T.Socket1.Get_Fd /= T.Socket2.Get_Fd, Message => "Descriptors collision!"); Nanomsg.Socket.Connect (T.Socket1, Address); Nanomsg.Socket.Bind (T.Socket2, "tcp://*:5555"); Begun := Ada.Calendar.Clock; for X in 1 .. 1_000_000 loop T.Socket1.Send (Msg1); T.Socket2.Receive (Msg2); end loop; Dur := Ada.Calendar.Clock - Begun; Ada.Text_Io.Put_Line ("Sending of million messages in pipeline mode took: " & Duration'Image (Dur) & " seconds"); Assert (Condition => Msg1.Text = Msg2.Text, Message => "Message transfer failed. Texts are not identical" & Ascii.Lf & "Sent: " & Msg1.Text & "; Received: " & Msg2.Text); end Run_Test; function Name (T : TC) return Message_String is begin return Aunit.Format ("Test case name : Message send/receive million messages"); end Name; procedure Tear_Down (T : in out Tc) is begin if T.Socket1.Get_Fd >= 0 then T.Socket1.Close; end if; if T.Socket2.Get_Fd >= 0 then T.Socket2.Close; end if; end Tear_Down; end Nanomsg.Test_Message_Send_Receive_Million;
-- The MIT License (MIT) -- Copyright (c) 2015 Pavel Zhukov <[email protected]> -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. with Ada.Calendar; with Ada.Text_Io; with Nanomsg.Domains; with Nanomsg.Pipeline; with Aunit.Assertions; with Nanomsg.Messages; package body Nanomsg.Test_Message_Send_Receive_Million is procedure Run_Test (T : in out TC) is use Aunit.Assertions; Address : constant String := "tcp://127.0.0.1:5555"; Msg1 : Nanomsg.Messages.Message_T; Msg2 : Nanomsg.Messages.Message_T := Nanomsg.Messages.Empty_Message; Begun : Ada.Calendar.Time; use type Ada.Calendar.Time; Dur : Duration; task Sender is entry Start; end Sender; task body Sender is begin accept Start; for X in 1 .. 1_000_000 loop T.Socket1.Send (Msg1); end loop; end Sender; begin Nanomsg.Messages.From_String (Msg1, "Hello world"); Nanomsg.Socket.Init (T.Socket1, Nanomsg.Domains.Af_Sp, Nanomsg.Pipeline.Nn_Push); Nanomsg.Socket.Init (T.Socket2, Nanomsg.Domains.Af_Sp, Nanomsg.Pipeline.Nn_Pull); Assert (Condition => not T.Socket1.Is_Null, Message => "Failed to initialize socket1"); Assert (Condition => not T.Socket2.Is_Null, Message => "Failed to initialize socket2"); Assert (Condition => T.Socket1.Get_Fd /= T.Socket2.Get_Fd, Message => "Descriptors collision!"); Nanomsg.Socket.Connect (T.Socket1, Address); Nanomsg.Socket.Bind (T.Socket2, "tcp://*:5555"); Begun := Ada.Calendar.Clock; Sender.Start; for X in 1 .. 1_000_000 loop T.Socket2.Receive (Msg2); end loop; Dur := Ada.Calendar.Clock - Begun; Ada.Text_Io.Put_Line ("Sending of million messages in pipeline mode took: " & Duration'Image (Dur) & " seconds"); Assert (Condition => Msg1.Text = Msg2.Text, Message => "Message transfer failed. Texts are not identical" & Ascii.Lf & "Sent: " & Msg1.Text & "; Received: " & Msg2.Text); end Run_Test; function Name (T : TC) return Message_String is begin return Aunit.Format ("Test case name : Message send/receive million messages"); end Name; procedure Tear_Down (T : in out Tc) is begin if T.Socket1.Get_Fd >= 0 then T.Socket1.Close; end if; if T.Socket2.Get_Fd >= 0 then T.Socket2.Close; end if; end Tear_Down; end Nanomsg.Test_Message_Send_Receive_Million;
Use dedicated thread for "one million test"
Use dedicated thread for "one million test" Before all messages were sent one by one. This was not right way to work with pipeline sockets. Using separate thread for sending message reduced time from 14 secs to 1.2 secs
Ada
mit
landgraf/nanomsg-ada
5a27a605efb4461458c9fa3f8a778ccd56bf71a7
awa/src/awa-components-wikis.adb
awa/src/awa-components-wikis.adb
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Render.Html; with Wiki.Writers; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String) is begin Writer.Writer.Write_Wide_Text (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write (Content); end Write; -- ------------------------------ -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. -- ------------------------------ overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Element (Name, Content); end Write_Wide_Element; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Parsers.Wiki_Syntax_Type is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" then return Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" then return Wiki.Parsers.SYNTAX_PHPBB; elsif Format = "creole" then return Wiki.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" then return Wiki.Parsers.SYNTAX_MEDIA_WIKI; else return Wiki.Parsers.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Get the links renderer that must be used to render image and page links. -- ------------------------------ function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Link_Renderer_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Link_Renderer_Access; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Renderer.Set_Writer (Html'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Util.Beans.Objects.To_Wide_Wide_String (Value), Format); end if; Writer.End_Element ("div"); end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin return Util.Beans.Objects.Null_Object; end Get_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; -- ------------------------------ -- Return true if the link is an absolute link. -- ------------------------------ function Is_Link_Absolute (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String) return Boolean is begin return Starts_With (Link, "http://") or Starts_With (Link, "https://"); end Is_Link_Absolute; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is begin if Renderer.Is_Link_Absolute (Link) then URI := Link; else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Ada.Characters.Conversions; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Render.Html; with Wiki.Writers; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String) is begin Writer.Writer.Write_Wide_Text (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write (Content); end Write; -- ------------------------------ -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. -- ------------------------------ overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Element (Name, Content); end Write_Wide_Element; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Parsers.Wiki_Syntax_Type is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" then return Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" then return Wiki.Parsers.SYNTAX_PHPBB; elsif Format = "creole" then return Wiki.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" then return Wiki.Parsers.SYNTAX_MEDIA_WIKI; else return Wiki.Parsers.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Get the links renderer that must be used to render image and page links. -- ------------------------------ function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Link_Renderer_Access is Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME); Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if Bean = null then return null; elsif not (Bean.all in Link_Renderer_Bean'Class) then return null; else return Link_Renderer_Bean'Class (Bean.all)'Access; end if; end Get_Links_Renderer; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; use type Wiki.Render.Link_Renderer_Access; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); Links : Wiki.Render.Link_Renderer_Access; begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Links := UI.Get_Links_Renderer (Context); if Links /= null then Renderer.Set_Link_Renderer (Links); end if; Renderer.Set_Writer (Html'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Util.Beans.Objects.To_Wide_Wide_String (Value), Format); end if; Writer.End_Element ("div"); end; end Encode_Begin; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = IMAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Image_Prefix); elsif Name = PAGE_PREFIX_ATTR then return Util.Beans.Objects.To_Object (From.Page_Prefix); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean is use Ada.Characters.Conversions; Pos : Positive := 1; begin if Length (Content) < Item'Length then return False; end if; for I in Item'Range loop if Item (I) /= To_Character (Element (Content, Pos)) then return False; end if; Pos := Pos + 1; end loop; return True; end Starts_With; -- ------------------------------ -- Return true if the link is an absolute link. -- ------------------------------ function Is_Link_Absolute (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String) return Boolean is begin return Starts_With (Link, "http://") or Starts_With (Link, "https://"); end Is_Link_Absolute; procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String) is begin if Renderer.Is_Link_Absolute (Link) then URI := Link; else URI := Prefix & Link; end if; end Make_Link; -- ------------------------------ -- Get the image link that must be rendered from the wiki image link. -- ------------------------------ overriding procedure Make_Image_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural) is begin Renderer.Make_Link (Link, Renderer.Image_Prefix, URI); Width := 0; Height := 0; end Make_Image_Link; -- ------------------------------ -- Get the page link that must be rendered from the wiki page link. -- ------------------------------ overriding procedure Make_Page_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean) is begin Renderer.Make_Link (Link, Renderer.Page_Prefix, URI); Exists := True; end Make_Page_Link; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
Update the Get_Value to return the image/page prefix attributes
Update the Get_Value to return the image/page prefix attributes
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
42926dc2f924ae7a2287a922bfed2522578f6030
awa/src/awa-components-wikis.adb
awa/src/awa-components-wikis.adb
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Beans.Objects; with ASF.Contexts.Writer; with ASF.Utils; with AWA.Wikis.Writers.Html; package body AWA.Components.Wikis is WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return AWA.Wikis.Parsers.Wiki_Syntax_Type is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" then return AWA.Wikis.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return AWA.Wikis.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" then return AWA.Wikis.Parsers.SYNTAX_PHPBB; elsif Format = "creole" then return AWA.Wikis.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" then return AWA.Wikis.Parsers.SYNTAX_MEDIA_WIKI; else return AWA.Wikis.Parsers.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased AWA.Wikis.Writers.Html.Html_Writer; Format : constant AWA.Wikis.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); begin Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Html.Set_Writer (Writer); AWA.Wikis.Parsers.Parse (Html'Unchecked_Access, Util.Beans.Objects.To_Wide_Wide_String (Value), Format); end if; Writer.End_Element ("div"); end; end Encode_Begin; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Beans.Objects; with Ada.Strings.Wide_Wide_Unbounded; with ASF.Contexts.Writer; with ASF.Utils; with Wiki.Render.Html; with Wiki.Writers; package body AWA.Components.Wikis is use Ada.Strings.Wide_Wide_Unbounded; WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record Writer : ASF.Contexts.Writer.Response_Writer_Access; end record; type Html_Writer_Type_Access is access all Html_Writer_Type'Class; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String); -- Write a single character to the string builder. overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Start an XML element with the given name. overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String); -- Closes an XML element of the given name. overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String); -- Write a text escaping any character as necessary. overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String); overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Wide_Wide_String) is begin Writer.Writer.Write_Wide_Text (Content); end Write; -- ------------------------------ -- Write a single character to the string builder. -- ------------------------------ overriding procedure Write (Writer : in out Html_Writer_Type; Char : in Wide_Wide_Character) is begin Writer.Writer.Write_Wide_Char (Char); end Write; overriding procedure Write (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write (Content); end Write; -- ------------------------------ -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. -- ------------------------------ overriding procedure Write_Wide_Element (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Element (Name, Content); end Write_Wide_Element; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type; Name : in String; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Attribute (Name, Content); end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.Start_Element (Name); end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Writer : in out Html_Writer_Type; Name : in String) is begin Writer.Writer.End_Element (Name); end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Writer : in out Html_Writer_Type; Content : in Unbounded_Wide_Wide_String) is begin Writer.Writer.Write_Wide_Text (Content); end Write_Wide_Text; -- ------------------------------ -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. -- ------------------------------ function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Parsers.Wiki_Syntax_Type is Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME, Context => Context, Default => "dotclear"); begin if Format = "dotclear" then return Wiki.Parsers.SYNTAX_DOTCLEAR; elsif Format = "google" then return Wiki.Parsers.SYNTAX_GOOGLE; elsif Format = "phpbb" then return Wiki.Parsers.SYNTAX_PHPBB; elsif Format = "creole" then return Wiki.Parsers.SYNTAX_CREOLE; elsif Format = "mediawiki" then return Wiki.Parsers.SYNTAX_MEDIA_WIKI; else return Wiki.Parsers.SYNTAX_MIX; end if; end Get_Wiki_Style; -- ------------------------------ -- Render the wiki text -- ------------------------------ overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class) is use ASF.Contexts.Writer; begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Html : aliased Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context); Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME); begin Html.Writer := Writer; Writer.Start_Element ("div"); UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer); if not Util.Beans.Objects.Is_Empty (Value) then Renderer.Set_Writer (Html'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Util.Beans.Objects.To_Wide_Wide_String (Value), Format); end if; Writer.End_Element ("div"); end; end Encode_Begin; begin ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES); end AWA.Components.Wikis;
Use the Ada Wiki library - implement the Html_Writer_Type to render the result in the ASF context writer - configure the HTML renderer
Use the Ada Wiki library - implement the Html_Writer_Type to render the result in the ASF context writer - configure the HTML renderer
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
affbf2d0cfbd9ff77fa057c334416ad79a80b12b
matp/src/mat-expressions.adb
matp/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Frames; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); Resolver : Resolver_Type_Access; -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; Region : MAT.Memory.Region_Info; begin if Resolver /= null then case Kind is when INSIDE_REGION | INSIDE_DIRECT_REGION => Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name)); when others => Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name)); end case; end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_HAS_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Event_Id_Type; Max : in MAT.Events.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Create an expression node to keep allocation events which don't have any associated free. -- ------------------------------ function Create_No_Free return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NO_FREE); return Result; end Create_No_Free; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Event); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when N_HAS_ADDR => return Addr <= Node.Min_Addr and Addr + Allocation.Size >= Node.Max_Addr; when N_IN_FUNC => return MAT.Frames.In_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Event_Id_Type; use type MAT.Events.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when N_IN_FUNC => return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String; Resolver : in Resolver_Type_Access) return Expression_Type is begin MAT.Expressions.Resolver := Resolver; return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Frames; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); Resolver : Resolver_Type_Access; -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; Region : MAT.Memory.Region_Info; begin if Resolver /= null then case Kind is when INSIDE_REGION | INSIDE_DIRECT_REGION => Region := Resolver.Find_Region (Ada.Strings.Unbounded.To_String (Name)); when others => Region := Resolver.Find_Symbol (Ada.Strings.Unbounded.To_String (Name)); end case; end if; if Kind = INSIDE_DIRECT_REGION or Kind = INSIDE_DIRECT_FUNCTION then Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC_DIRECT, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); else Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_IN_FUNC, Min_Addr => Region.Start_Addr, Max_Addr => Region.End_Addr); end if; return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_HAS_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Event_Id_Type; Max : in MAT.Events.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Create an expression node to keep allocation events which don't have any associated free. -- ------------------------------ function Create_No_Free return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NO_FREE); return Result; end Create_No_Free; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Event); end if; end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when N_HAS_ADDR => return Addr <= Node.Min_Addr and Addr + Allocation.Size >= Node.Max_Addr; when N_IN_FUNC => return MAT.Frames.In_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Allocation.Frame, Node.Min_Addr, Node.Max_Addr); when N_THREAD => return Allocation.Thread >= Node.Min_Thread and Allocation.Thread <= Node.Max_Thread; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Target_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Event_Id_Type; use type MAT.Events.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when N_HAS_ADDR => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Addr <= Node.Min_Addr and Event.Addr + Event.Size >= Node.Max_Addr; end if; return False; when N_NO_FREE => if Event.Index = MAT.Events.MSG_MALLOC or Event.Index = MAT.Events.MSG_REALLOC then return Event.Next_Id = 0; else return False; end if; when N_IN_FUNC => return MAT.Frames.In_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when N_IN_FUNC_DIRECT => return MAT.Frames.By_Function (Event.Frame, Node.Min_Addr, Node.Max_Addr); when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String; Resolver : in Resolver_Type_Access) return Expression_Type is begin MAT.Expressions.Resolver := Resolver; return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Implement the N_THREAD selection on the memory allocation
Implement the N_THREAD selection on the memory allocation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
f26e6a999707daeb54299edce9acee4c0843983b
awa/plugins/awa-comments/src/awa-comments-beans.adb
awa/plugins/awa-comments/src/awa-comments-beans.adb
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with ADO.Parameters; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; else AWA.Comments.Models.Comment_Bean (From).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- ------------------------------ -- Save the comment. -- ------------------------------ overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Update_Comment (Permission => To_String (Bean.Permission), Comment => Bean); end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); elsif Name = "sort" then if Util.Beans.Objects.To_String (Value) = "oldest" then From.Oldest_First := True; else From.Oldest_First := False; end if; elsif Name = "status" then if Util.Beans.Objects.To_String (Value) = "published" then From.Publish_Only := True; else From.Publish_Only := False; end if; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; if Into.Publish_Only then Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); else Query.Set_Query (AWA.Comments.Models.Query_All_Comment_List); end if; Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); if Into.Oldest_First then Query.Bind_Param ("sort", ADO.Parameters.Token '("ASC")); else Query.Bind_Param ("sort", ADO.Parameters.Token '("DESC")); end if; AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014, 2015, 2016, 2017, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with ADO.Parameters; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" and then not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; else AWA.Comments.Models.Comment_Bean (From).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- ------------------------------ -- Save the comment. -- ------------------------------ overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Update_Comment (Permission => To_String (Bean.Permission), Comment => Bean); end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); elsif Name = "sort" then if Util.Beans.Objects.To_String (Value) = "oldest" then From.Oldest_First := True; else From.Oldest_First := False; end if; elsif Name = "status" then if Util.Beans.Objects.To_String (Value) = "published" then From.Publish_Only := True; else From.Publish_Only := False; end if; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; if Into.Publish_Only then Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); else Query.Set_Query (AWA.Comments.Models.Query_All_Comment_List); end if; Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); if Into.Oldest_First then Query.Bind_Param ("sort", ADO.Parameters.Token '("ASC")); else Query.Bind_Param ("sort", ADO.Parameters.Token '("DESC")); end if; AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
Fix style warnings: add missing overriding and update and then/or else conditions
Fix style warnings: add missing overriding and update and then/or else conditions
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1aabe08b9e7ec6bd302d24eebc7ecdbc1221db26
src/util-properties.ads
src/util-properties.ads
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 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.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; private with Util.Beans.Objects.Maps; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Ada.Strings.Unbounded.Unbounded_String; function "+" (S : String) return Value renames To_Unbounded_String; function "-" (S : Value) return String renames To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Value) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Value); -- 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)); type Name_Array is array (Natural range <>) of Value; -- Return the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with -- the prefix are returned. function Get_Names (Self : in Manager; Prefix : in String := "") return Name_Array; -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- 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); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 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.Strings.Unbounded; with Ada.Finalization; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Ada.Strings.Unbounded.Unbounded_String; function "+" (S : String) return Value renames To_Unbounded_String; function "-" (S : Value) return String renames To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Value) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return Value; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Value) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Value); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Value); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Value); -- 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 : in String; Item : in Util.Beans.Objects.Object)); -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- 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); private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Util.Beans.Objects.Object)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
Refactor the Properties implementation (step 4): - Change the Iterate procedure to get the Name/Value as String and Object - Remove the Get_Names function and Name_Array type
Refactor the Properties implementation (step 4): - Change the Iterate procedure to get the Name/Value as String and Object - Remove the Get_Names function and Name_Array type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
96d6956ef0fb6bd0ec75251dba43dc1c858e27a1
testutil/util-tests.ads
testutil/util-tests.ads
----------------------------------------------------------------------- -- AUnit utils - Helper for writing unit tests -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with GNAT.Source_Info; with Util.Properties; with Util.Assertions; with Util.XUnit; package Util.Tests is use Ada.Strings.Unbounded; subtype Message_String is Util.XUnit.Message_String; subtype Test_Case is Util.XUnit.Test_Case; subtype Test_Suite is Util.XUnit.Test_Suite; subtype Access_Test_Suite is Util.XUnit.Access_Test_Suite; function Format (S : in String) return Message_String renames Util.XUnit.Format; type Test is new Util.XUnit.Test with null record; -- Get a path to access a test file. function Get_Path (File : String) return String; -- Get a path to create a test file. function Get_Test_Path (File : String) return String; -- Get the timeout for the test execution. function Get_Test_Timeout (Name : in String) return Duration; -- Get the testsuite harness prefix. This prefix is added to the test class name. -- By default it is empty. It is allows to execute the test harness on different -- environment (ex: MySQL or SQLlite) and be able to merge and collect the two result -- sets together. function Get_Harness_Prefix return String; -- Get a test configuration parameter. function Get_Parameter (Name : String; Default : String := "") return String; -- Get the test configuration properties. function Get_Properties return Util.Properties.Manager; -- Get a new unique string function Get_Uuid return String; -- Check that two files are equal. This is intended to be used by -- tests that create files that are then checked against patterns. procedure Assert_Equal_Files (T : in Test_Case'Class; Expect : in String; Test : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Integer); procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Character); -- Check that the value matches what we expect. -- procedure Assert (T : in Test'Class; -- Condition : in Boolean; -- Message : in String := "Test failed"; -- Source : String := GNAT.Source_Info.File; -- Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect, Value : in Ada.Calendar.Time; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect, Value : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect : in String; Value : in Unbounded_String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches the regular expression procedure Assert_Matches (T : in Test'Class; Pattern : in String; Value : in Unbounded_String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches the regular expression procedure Assert_Matches (T : in Test'Class; Pattern : in String; Value : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Default initialization procedure. procedure Initialize_Test (Props : in Util.Properties.Manager); -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. generic with function Suite return Access_Test_Suite; with procedure Initialize (Props : in Util.Properties.Manager) is Initialize_Test; procedure Harness (Name : in String); end Util.Tests;
----------------------------------------------------------------------- -- AUnit utils - Helper for writing unit tests -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with GNAT.Source_Info; with Util.Properties; with Util.Assertions; with Util.XUnit; package Util.Tests is use Ada.Strings.Unbounded; subtype Message_String is Util.XUnit.Message_String; subtype Test_Case is Util.XUnit.Test_Case; subtype Test_Suite is Util.XUnit.Test_Suite; subtype Access_Test_Suite is Util.XUnit.Access_Test_Suite; function Format (S : in String) return Message_String renames Util.XUnit.Format; type Test is new Util.XUnit.Test with null record; -- Get a path to access a test file. function Get_Path (File : String) return String; -- Get a path to create a test file. function Get_Test_Path (File : String) return String; -- Get the timeout for the test execution. function Get_Test_Timeout (Name : in String) return Duration; -- Get the testsuite harness prefix. This prefix is added to the test class name. -- By default it is empty. It is allows to execute the test harness on different -- environment (ex: MySQL or SQLlite) and be able to merge and collect the two result -- sets together. function Get_Harness_Prefix return String; -- Get a test configuration parameter. function Get_Parameter (Name : String; Default : String := "") return String; -- Get the test configuration properties. function Get_Properties return Util.Properties.Manager; -- Get a new unique string function Get_Uuid return String; -- Check that two files are equal. This is intended to be used by -- tests that create files that are then checked against patterns. procedure Assert_Equal_Files (T : in Test_Case'Class; Expect : in String; Test : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Integer); procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Character); procedure Assert_Equals is new Assertions.Assert_Equals_T (Value_Type => Long_Long_Integer); -- Check that the value matches what we expect. -- procedure Assert (T : in Test'Class; -- Condition : in Boolean; -- Message : in String := "Test failed"; -- Source : String := GNAT.Source_Info.File; -- Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect, Value : in Ada.Calendar.Time; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect, Value : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches what we expect. procedure Assert_Equals (T : in Test'Class; Expect : in String; Value : in Unbounded_String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches the regular expression procedure Assert_Matches (T : in Test'Class; Pattern : in String; Value : in Unbounded_String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Check that the value matches the regular expression procedure Assert_Matches (T : in Test'Class; Pattern : in String; Value : in String; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line); -- Default initialization procedure. procedure Initialize_Test (Props : in Util.Properties.Manager); -- The main testsuite program. This launches the tests, collects the -- results, create performance logs and set the program exit status -- according to the testsuite execution status. generic with function Suite return Access_Test_Suite; with procedure Initialize (Props : in Util.Properties.Manager) is Initialize_Test; procedure Harness (Name : in String); end Util.Tests;
Add an Assert_Equals on Long_Long_Integer type
Add an Assert_Equals on Long_Long_Integer type
Ada
apache-2.0
Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util,Letractively/ada-util
43687146b07051c9e62c284f912155092a5495b4
src/sqlite/ado-drivers-connections-sqlite.adb
src/sqlite/ado-drivers-connections-sqlite.adb
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.C; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, ADO.C.To_C (SQL_Stat), No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free -- Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Result := Sqlite3_H.sqlite3_close (Database.Server); Database.Server := System.Null_Address; pragma Unreferenced (Result); end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; DB : Ref.Ref; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is pragma Unreferenced (D); use Strings; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if not DB.Is_Null then Result := Ref.Create (DB.Value); return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name : in String; Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := Util.Properties.To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name : in String; Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item); begin if Util.Strings.Index (Name, '.') = 0 then Log.Info ("Configure database with {0}", SQL); Database.Execute (SQL); end if; end Configure; begin Database.Server := Handle; Database.Name := Config.Database; DB := Ref.Create (Database.all'Access); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 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 System; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.C; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : access Sqlite3; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, ADO.C.To_C (SQL_Stat), No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free -- Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); if Database.Server /= null then Result := Sqlite3_H.sqlite3_close (Database.Server); Database.Server := null; end if; pragma Unreferenced (Result); end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; DB : Ref.Ref; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is pragma Unreferenced (D); use Strings; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased access Sqlite3; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if not DB.Is_Null then Result := Ref.Create (DB.Value); return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Address, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then -- declare -- Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); -- Msg : constant String := Strings.Value (Error); -- begin -- Log.Error ("Error {0}: {1}", int'Image (Result), Msg); -- end; raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name : in String; Item : in Util.Properties.Value); function Escape (Value : in Util.Properties.Value) return String; function Escape (Value : in Util.Properties.Value) return String is S : constant String := Util.Properties.To_String (Value); begin if S'Length > 0 and then S (S'First) >= '0' and then S (S'First) <= '9' then return S; elsif S'Length > 0 and then S (S'First) = ''' then return S; else return "'" & S & "'"; end if; end Escape; procedure Configure (Name : in String; Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & Name & "=" & Escape (Item); begin if Util.Strings.Index (Name, '.') = 0 then Log.Info ("Configure database with {0}", SQL); Database.Execute (SQL); end if; end Configure; begin Database.Server := Handle; Database.Name := Config.Database; DB := Ref.Create (Database.all'Access); -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
Replace Sqlite_Access and System.Address with the access Sqlite3 type
Replace Sqlite_Access and System.Address with the access Sqlite3 type
Ada
apache-2.0
stcarrez/ada-ado
0bc4eba3c24e15d77b29f64f035da7dd867f7721
src/asf-components-html.adb
src/asf-components-html.adb
----------------------------------------------------------------------- -- html -- ASF HTML Components -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package body ASF.Components.Html is use EL.Objects; procedure Render_Attributes (UI : in UIHtmlComponent; Context : in out Faces_Context'Class; Writer : in ResponseWriter_Access) is Style : constant Object := UI.Get_Attribute (Context, "style"); Class : constant Object := UI.Get_Attribute (Context, "styleClass"); begin Writer.Write_Attribute ("id", UI.Get_Client_Id); if not Is_Null (Class) then Writer.Write_Attribute ("class", Class); end if; if not Is_Null (Style) then Writer.Write_Attribute ("style", Style); end if; end Render_Attributes; end ASF.Components.Html;
----------------------------------------------------------------------- -- html -- ASF HTML Components -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; package body ASF.Components.Html is use EL.Objects; procedure Render_Attributes (UI : in UIHtmlComponent; Context : in out Faces_Context'Class; Writer : in ResponseWriter_Access) is Style : constant Object := UI.Get_Attribute (Context, "style"); Class : constant Object := UI.Get_Attribute (Context, "styleClass"); Title : constant Object := UI.Get_Attribute (Context, "title"); begin Writer.Write_Attribute ("id", UI.Get_Client_Id); if not Is_Null (Class) then Writer.Write_Attribute ("class", Class); end if; if not Is_Null (Style) then Writer.Write_Attribute ("style", Style); end if; if not Is_Null (Title) then Writer.Write_Attribute ("title", Title); end if; end Render_Attributes; end ASF.Components.Html;
Add support for the title attribute
Add support for the title attribute
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
a2042aa6ff7c3b7d89902cd431d6bbc6bb7a10cf
src/asf-views-nodes-jsf.adb
src/asf-views-nodes-jsf.adb
----------------------------------------------------------------------- -- 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.Converters; with ASF.Validators.Texts; with ASF.Validators.Numbers; with ASF.Components.Holders; with ASF.Components.Core.Views; package body ASF.Views.Nodes.Jsf is use ASF; use EL.Objects; -- ------------------------------ -- Converter Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node; Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes, "converterId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Conv = null then Node.Error ("Missing 'converterId' attribute"); else Node.Converter := EL.Objects.To_Object (Conv.Value); end if; return Node.all'Access; end Create_Converter_Tag_Node; -- ------------------------------ -- 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) is use ASF.Components.Holders; use type ASF.Converters.Converter_Access; Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter); begin if not (Parent.all in Value_Holder'Class) then Node.Error ("Parent component is not an instance of Value_Holder"); return; end if; if Cvt = null then Node.Error ("Converter was not found"); return; end if; declare VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access; begin VH.Set_Converter (Converter => Cvt); end; end Build_Components; -- ------------------------------ -- Validator Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node; Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes, "validatorId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Vid = null then Node.Error ("Missing 'validatorId' attribute"); else Node.Validator := EL.Objects.To_Object (Vid.Value); end if; return Node.all'Access; end Create_Validator_Tag_Node; -- ------------------------------ -- 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) is use ASF.Components.Holders; use type ASF.Validators.Validator_Access; V : Validators.Validator_Access; Shared : Boolean; begin if not (Parent.all in Editable_Value_Holder'Class) then Node.Error ("Parent component is not an instance of Editable_Value_Holder"); return; end if; Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared); if V = null then Node.Error ("Validator was not found"); return; end if; declare VH : constant access Editable_Value_Holder'Class := Editable_Value_Holder'Class (Parent.all)'Access; begin VH.Add_Validator (Validator => V, Shared => Shared); end; end Build_Components; -- ------------------------------ -- 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) is begin Validator := Context.Get_Validator (Node.Validator); Shared := True; end Get_Validator; -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Range_Validator_Tag_Node; -- 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) is use type ASF.Validators.Validator_Access; Min : Long_Long_Integer := Long_Long_Integer'First; Max : Long_Long_Integer := Long_Long_Integer'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context)); end if; if Node.Maximum /= null then Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context)); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max)); return; end if; Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Length_Validator_Tag_Node; -- ------------------------------ -- 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) is use type ASF.Validators.Validator_Access; Min : Natural := 0; Max : Natural := Natural'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context))); end if; if Node.Maximum /= null then Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context))); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Natural'Image (Min), Natural'Image (Max)); return; end if; Validator := Validators.Texts.Create_Length_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Attribute Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name"); Node : Attribute_Tag_Node_Access; begin Node := new Attribute_Tag_Node; Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Attr_Name := Attr; Node.Value := Find_Attribute (Attributes, "value"); if Node.Attr_Name = null then Node.Error ("Missing 'name' attribute"); else Node.Attr.Name := Attr.Value; end if; if Node.Value = null then Node.Error ("Missing 'value' attribute"); end if; return Node.all'Access; end Create_Attribute_Tag_Node; -- ------------------------------ -- 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) is use EL.Expressions; begin if Node.Attr_Name /= null and Node.Value /= null then if Node.Value.Binding /= null then declare Expr : constant EL.Expressions.Expression := ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context); begin Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr); end; else Parent.Set_Attribute (Def => Node.Attr'Access, Value => Get_Value (Node.Value.all, Context)); end if; end if; end Build_Components; -- ------------------------------ -- Facet Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Facet_Name := Find_Attribute (Attributes, "name"); if Node.Facet_Name = null then Node.Error ("Missing 'name' attribute"); end if; return Node.all'Access; end Create_Facet_Tag_Node; -- ------------------------------ -- 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) is begin null; end Build_Components; -- ------------------------------ -- Metadata Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); return Node.all'Access; end Create_Metadata_Tag_Node; -- ------------------------------ -- 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) is use ASF.Components.Core.Views; begin if not (Parent.all in UIView'Class) then Node.Error ("Parent component of <f:metadata> must be a <f:view>"); return; end if; declare UI : constant UIViewMetaData_Access := new UIViewMetaData; begin UIView'Class (Parent.all).Set_Metadata (UI, Node); Build_Attributes (UI.all, Node.all, Context); UI.Initialize (UI.Get_Context.all); Node.Build_Children (UI.all'Access, Context); end; end Build_Components; 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.Converters; with ASF.Validators.Texts; with ASF.Validators.Numbers; with ASF.Components.Holders; with ASF.Components.Core.Views; package body ASF.Views.Nodes.Jsf is -- ------------------------------ -- Converter Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node; Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes, "converterId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Conv = null then Node.Error ("Missing 'converterId' attribute"); else Node.Converter := EL.Objects.To_Object (Conv.Value); end if; return Node.all'Access; end Create_Converter_Tag_Node; -- ------------------------------ -- 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) is use ASF.Components.Holders; use type ASF.Converters.Converter_Access; Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter); begin if not (Parent.all in Value_Holder'Class) then Node.Error ("Parent component is not an instance of Value_Holder"); return; end if; if Cvt = null then Node.Error ("Converter was not found"); return; end if; declare VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access; begin VH.Set_Converter (Converter => Cvt); end; end Build_Components; -- ------------------------------ -- Validator Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node; Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes, "validatorId"); begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); if Vid = null then Node.Error ("Missing 'validatorId' attribute"); else Node.Validator := EL.Objects.To_Object (Vid.Value); end if; return Node.all'Access; end Create_Validator_Tag_Node; -- ------------------------------ -- 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) is use ASF.Components.Holders; use type ASF.Validators.Validator_Access; V : Validators.Validator_Access; Shared : Boolean; begin if not (Parent.all in Editable_Value_Holder'Class) then Node.Error ("Parent component is not an instance of Editable_Value_Holder"); return; end if; Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared); if V = null then Node.Error ("Validator was not found"); return; end if; declare VH : constant access Editable_Value_Holder'Class := Editable_Value_Holder'Class (Parent.all)'Access; begin VH.Add_Validator (Validator => V, Shared => Shared); end; end Build_Components; -- ------------------------------ -- 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) is begin Validator := Context.Get_Validator (Node.Validator); Shared := True; end Get_Validator; -- ------------------------------ -- Range Validator Tag -- ------------------------------ -- 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 Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Range_Validator_Tag_Node; -- 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) is use type ASF.Validators.Validator_Access; Min : Long_Long_Integer := Long_Long_Integer'First; Max : Long_Long_Integer := Long_Long_Integer'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context)); end if; if Node.Maximum /= null then Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context)); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max)); return; end if; Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Length Validator Tag -- ------------------------------ -- ------------------------------ -- 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 Nodes.Tag_Attribute_Array_Access) return Views.Nodes.Tag_Node_Access is use ASF.Views.Nodes; Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Minimum := Find_Attribute (Attributes, "minimum"); Node.Maximum := Find_Attribute (Attributes, "maximum"); if Node.Minimum = null and Node.Maximum = null then Node.Error ("Missing 'minimum' or 'maximum' attribute"); end if; return Node.all'Access; end Create_Length_Validator_Tag_Node; -- ------------------------------ -- 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) is use type ASF.Validators.Validator_Access; Min : Natural := 0; Max : Natural := Natural'Last; begin -- Get the minimum and maximum attributes. begin if Node.Minimum /= null then Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context))); end if; if Node.Maximum /= null then Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context))); end if; exception when Constraint_Error => Node.Error ("Invalid minimum or maximum value"); end; Shared := False; if Max < Min then Node.Error ("Minimum ({0}) should be less than maximum ({1})", Natural'Image (Min), Natural'Image (Max)); return; end if; Validator := Validators.Texts.Create_Length_Validator (Minimum => Min, Maximum => Max); end Get_Validator; -- ------------------------------ -- Attribute Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name"); Node : Attribute_Tag_Node_Access; begin Node := new Attribute_Tag_Node; Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Attr_Name := Attr; Node.Value := Find_Attribute (Attributes, "value"); if Node.Attr_Name = null then Node.Error ("Missing 'name' attribute"); else Node.Attr.Name := Attr.Value; end if; if Node.Value = null then Node.Error ("Missing 'value' attribute"); end if; return Node.all'Access; end Create_Attribute_Tag_Node; -- ------------------------------ -- 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) is use EL.Expressions; begin if Node.Attr_Name /= null and Node.Value /= null then if Node.Value.Binding /= null then declare Expr : constant EL.Expressions.Expression := ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context); begin Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr); end; else Parent.Set_Attribute (Def => Node.Attr'Access, Value => Get_Value (Node.Value.all, Context)); end if; end if; end Build_Components; -- ------------------------------ -- Facet Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); Node.Facet_Name := Find_Attribute (Attributes, "name"); if Node.Facet_Name = null then Node.Error ("Missing 'name' attribute"); end if; return Node.all'Access; end Create_Facet_Tag_Node; -- ------------------------------ -- 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) is begin null; end Build_Components; -- ------------------------------ -- Metadata Tag -- ------------------------------ -- ------------------------------ -- 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 is use ASF.Views.Nodes; Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node; begin Initialize (Node.all'Access, Binding, Line, Parent, Attributes); return Node.all'Access; end Create_Metadata_Tag_Node; -- ------------------------------ -- 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) is use ASF.Components.Core.Views; begin if not (Parent.all in UIView'Class) then Node.Error ("Parent component of <f:metadata> must be a <f:view>"); return; end if; declare UI : constant UIViewMetaData_Access := new UIViewMetaData; begin UIView'Class (Parent.all).Set_Metadata (UI, Node); Build_Attributes (UI.all, Node.all, Context); UI.Initialize (UI.Get_Context.all); Node.Build_Children (UI.all'Access, Context); end; end Build_Components; end ASF.Views.Nodes.Jsf;
Fix some compilation warnings
Fix some compilation warnings
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
015ea8d7d8d0a6b91234325f46ee93e03457f649
src/asf-beans.adb
src/asf-beans.adb
----------------------------------------------------------------------- -- asf.beans -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Objects.Maps; package body ASF.Beans is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Beans"); -- ------------------------------ -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access) is begin Log.Info ("Register bean class {0}", Name); Factory.Registry.Include (Name, Class_Binding_Ref.Create (Class)); end Register_Class; -- ------------------------------ -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Handler : in Create_Bean_Access) is Class : constant Default_Class_Binding_Access := new Default_Class_Binding; begin Class.Create := Handler; Register_Class (Factory, Name, Class.all'Access); end Register_Class; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is begin Log.Info ("Register bean '{0}' created by '{1}' in scope {2}", Name, Class, Scope_Type'Image (Scope)); declare Pos : constant Registry_Maps.Cursor := Factory.Registry.Find (Class); Binding : Bean_Binding; begin if not Registry_Maps.Has_Element (Pos) then Log.Error ("Class '{0}' does not exist. Cannot register bean '{1}'", Class, Name); return; end if; Binding.Create := Registry_Maps.Element (Pos); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end; end Register; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is Binding : Bean_Binding; begin Log.Info ("Register bean '{0}' in scope {2}", Name, Scope_Type'Image (Scope)); Binding.Create := Class_Binding_Ref.Create (Class); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end Register; -- ------------------------------ -- Register all the definitions from a factory to a main factory. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory) is begin declare Pos : Registry_Maps.Cursor := From.Registry.First; begin while Registry_Maps.Has_Element (Pos) loop Factory.Registry.Include (Key => Registry_Maps.Key (Pos), New_Item => Registry_Maps.Element (Pos)); Registry_Maps.Next (Pos); end loop; end; declare Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map); begin while Bean_Maps.Has_Element (Pos) loop Factory.Map.Include (Key => Bean_Maps.Key (Pos), New_Item => Bean_Maps.Element (Pos)); Bean_Maps.Next (Pos); end loop; end; end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type) is use type Util.Beans.Basic.Readonly_Bean_Access; Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare Binding : constant Bean_Binding := Bean_Maps.Element (Pos); begin Binding.Create.Value.Create (Name, Result); if Result /= null and then not Binding.Params.Is_Null then if Result.all in Util.Beans.Basic.Bean'Class then EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Result.all), Binding.Params.Value.Params, Context); else Log.Warn ("Bean {0} cannot be set with pre-defined properties as it does " & "not implement the Bean interface", To_String (Name)); end if; end if; Scope := Binding.Scope; end; else Result := null; Scope := ANY_SCOPE; end if; end Create; -- ------------------------------ -- Create a bean by using the registered create function. -- ------------------------------ procedure Create (Factory : in Default_Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); begin Result := Factory.Create.all; end Create; -- ------------------------------ -- Create a map bean object that allows to associate name/value pairs in a bean. -- ------------------------------ function Create_Map_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Util.Beans.Objects.Maps.Map_Bean; end Create_Map_Bean; end ASF.Beans;
----------------------------------------------------------------------- -- asf.beans -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Beans.Objects.Maps; package body ASF.Beans is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Beans"); -- ------------------------------ -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access) is begin Log.Info ("Register bean class {0}", Name); Factory.Registry.Include (Name, Class_Binding_Ref.Create (Class)); end Register_Class; -- ------------------------------ -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Handler : in Create_Bean_Access) is Class : constant Default_Class_Binding_Access := new Default_Class_Binding; begin Class.Create := Handler; Register_Class (Factory, Name, Class.all'Access); end Register_Class; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is begin Log.Info ("Register bean '{0}' created by '{1}' in scope {2}", Name, Class, Scope_Type'Image (Scope)); declare Pos : constant Registry_Maps.Cursor := Factory.Registry.Find (Class); Binding : Bean_Binding; begin if not Registry_Maps.Has_Element (Pos) then Log.Error ("Class '{0}' does not exist. Cannot register bean '{1}'", Class, Name); return; end if; Binding.Create := Registry_Maps.Element (Pos); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end; end Register; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is Binding : Bean_Binding; begin Log.Info ("Register bean '{0}' in scope {1}", Name, Scope_Type'Image (Scope)); Binding.Create := Class_Binding_Ref.Create (Class); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end Register; -- ------------------------------ -- Register all the definitions from a factory to a main factory. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory) is begin declare Pos : Registry_Maps.Cursor := From.Registry.First; begin while Registry_Maps.Has_Element (Pos) loop Factory.Registry.Include (Key => Registry_Maps.Key (Pos), New_Item => Registry_Maps.Element (Pos)); Registry_Maps.Next (Pos); end loop; end; declare Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map); begin while Bean_Maps.Has_Element (Pos) loop Factory.Map.Include (Key => Bean_Maps.Key (Pos), New_Item => Bean_Maps.Element (Pos)); Bean_Maps.Next (Pos); end loop; end; end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type) is use type Util.Beans.Basic.Readonly_Bean_Access; Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare Binding : constant Bean_Binding := Bean_Maps.Element (Pos); begin Binding.Create.Value.Create (Name, Result); if Result /= null and then not Binding.Params.Is_Null then if Result.all in Util.Beans.Basic.Bean'Class then EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Result.all), Binding.Params.Value.Params, Context); else Log.Warn ("Bean {0} cannot be set with pre-defined properties as it does " & "not implement the Bean interface", To_String (Name)); end if; end if; Scope := Binding.Scope; end; else Result := null; Scope := ANY_SCOPE; end if; end Create; -- ------------------------------ -- Create a bean by using the registered create function. -- ------------------------------ procedure Create (Factory : in Default_Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); begin Result := Factory.Create.all; end Create; -- ------------------------------ -- Create a map bean object that allows to associate name/value pairs in a bean. -- ------------------------------ function Create_Map_Bean return Util.Beans.Basic.Readonly_Bean_Access is begin return new Util.Beans.Objects.Maps.Map_Bean; end Create_Map_Bean; end ASF.Beans;
Fix log when a bean is registered
Fix log when a bean is registered
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
112313da668ba10967619c442bd41c71859f7f12
src/orka/interface/orka-transforms-simd_vectors.ads
src/orka/interface/orka-transforms-simd_vectors.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. with Orka.SIMD; generic type Element_Type is digits <>; type Vector_Type is array (SIMD.Index_Homogeneous) of Element_Type; with function "*" (Left, Right : Vector_Type) return Vector_Type; with function Add_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Subtract_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Minus_Vector (Elements : Vector_Type) return Vector_Type; with function Absolute_Vector (Elements : Vector_Type) return Vector_Type; with function Sum (Elements : Vector_Type) return Element_Type; with function Divide_Or_Zero (Left, Right : Vector_Type) return Vector_Type; with function Cross_Product (Left, Right : Vector_Type) return Vector_Type; package Orka.Transforms.SIMD_Vectors is pragma Preelaborate; subtype Vector4 is Vector_Type; function Zero_Value return Vector_Type is ((0.0, 0.0, 0.0, 0.0)) with Inline; function "+" (Left, Right : Vector_Type) return Vector_Type renames Add_Vectors; function "-" (Left, Right : Vector_Type) return Vector_Type renames Subtract_Vectors; function "-" (Elements : Vector_Type) return Vector_Type renames Minus_Vector; function "abs" (Elements : Vector_Type) return Vector_Type renames Absolute_Vector; function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type; function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type; function Magnitude2 (Elements : Vector_Type) return Element_Type with Inline; function Magnitude (Elements : Vector_Type) return Element_Type; function Normalize (Elements : Vector_Type) return Vector_Type; function Normalized (Elements : Vector_Type) return Boolean; function Distance (Left, Right : Vector_Type) return Element_Type; function Projection (Elements, Direction : Vector_Type) return Vector_Type; function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type; function Angle (Left, Right : Vector_Type) return Element_Type; function Dot (Left, Right : Vector_Type) return Element_Type; function Cross (Left, Right : Vector_Type) return Vector_Type renames Cross_Product; end Orka.Transforms.SIMD_Vectors;
-- 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 Orka.SIMD; generic type Element_Type is digits <>; type Vector_Type is array (SIMD.Index_Homogeneous) of Element_Type; with function "*" (Left, Right : Vector_Type) return Vector_Type; with function Add_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Subtract_Vectors (Left, Right : Vector_Type) return Vector_Type; with function Minus_Vector (Elements : Vector_Type) return Vector_Type; with function Absolute_Vector (Elements : Vector_Type) return Vector_Type; with function Sum (Elements : Vector_Type) return Element_Type; with function Divide_Or_Zero (Left, Right : Vector_Type) return Vector_Type; with function Cross_Product (Left, Right : Vector_Type) return Vector_Type; package Orka.Transforms.SIMD_Vectors is pragma Preelaborate; subtype Vector4 is Vector_Type; function Zero_Direction return Vector_Type is ((0.0, 0.0, 0.0, 0.0)) with Inline; function Zero_Point return Vector_Type is ((0.0, 0.0, 0.0, 1.0)) with Inline; function "+" (Left, Right : Vector_Type) return Vector_Type renames Add_Vectors; function "-" (Left, Right : Vector_Type) return Vector_Type renames Subtract_Vectors; function "-" (Elements : Vector_Type) return Vector_Type renames Minus_Vector; function "abs" (Elements : Vector_Type) return Vector_Type renames Absolute_Vector; function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type; function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type; function Magnitude2 (Elements : Vector_Type) return Element_Type with Inline; function Magnitude (Elements : Vector_Type) return Element_Type; function Normalize (Elements : Vector_Type) return Vector_Type; function Normalized (Elements : Vector_Type) return Boolean; function Distance (Left, Right : Vector_Type) return Element_Type; function Projection (Elements, Direction : Vector_Type) return Vector_Type; function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type; function Angle (Left, Right : Vector_Type) return Element_Type; function Dot (Left, Right : Vector_Type) return Element_Type; function Cross (Left, Right : Vector_Type) return Vector_Type renames Cross_Product; end Orka.Transforms.SIMD_Vectors;
Replace Zero_Value with Zero_Direction and Zero_Point
orka: Replace Zero_Value with Zero_Direction and Zero_Point Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
54dfeae8df44537b1483913ab45cdbf5cae1cb6d
src/ado-sessions-factory.ads
src/ado-sessions-factory.ads
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences; with ADO.Caches; with ADO.Sessions.Sources; -- == Session Factory == -- The session factory is the entry point to obtain a database session. -- The `ADO.Sessions.Factory` package defines the factory for creating -- sessions. -- -- with ADO.Sessions.Factory; -- ... -- Sess_Factory : ADO.Sessions.Factory; -- -- The session factory can be initialized by using the `Create` operation and -- by giving a URI string that identifies the driver and the information to connect -- to the database. The session factory is created only once when the application starts. -- -- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test"); -- -- Having a session factory, one can get a database by using the `Get_Session` or -- `Get_Master_Session` function. Each time this operation is called, a new session -- is returned. The session is released when the session variable is finalized. -- -- DB : ADO.Sessions.Session := Sess_Factory.Get_Session; -- -- The session factory is also responsible for maintaining some data that is shared by -- all the database connections. This includes: -- -- * the sequence generators used to allocate unique identifiers for database tables, -- * the entity cache, -- * some application specific global cache. -- package ADO.Sessions.Factory is pragma Elaborate_Body; ENTITY_CACHE_NAME : constant String := "entity_type"; -- ------------------------------ -- Session factory -- ------------------------------ type Session_Factory is tagged limited private; type Session_Factory_Access is access all Session_Factory'Class; -- Get a read-only session from the factory. function Get_Session (Factory : in Session_Factory) return Session; -- Get a read-write session from the factory. function Get_Master_Session (Factory : in Session_Factory) return Master_Session; -- Open a session procedure Open_Session (Factory : in out Session_Factory; Database : out Session); -- Open a session procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session); -- Create the session factory to connect to the database represented -- by the data source. procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source); -- Create the session factory to connect to the database identified -- by the URI. procedure Create (Factory : out Session_Factory; URI : in String); -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. function Get_Session (Proxy : in Session_Record_Access) return Session; private -- The session factory holds the necessary information to obtain a master or slave -- database connection. The sequence factory is shared by all sessions of the same -- factory (implementation is thread-safe). The factory also contains the entity type -- cache which is initialized when the factory is created. type Session_Factory is tagged limited record Source : ADO.Sessions.Sources.Data_Source; Sequences : Factory_Access := null; Seq_Factory : aliased ADO.Sequences.Factory; -- Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache; Entities : ADO.Sessions.Entity_Cache_Access := null; Cache : aliased ADO.Caches.Cache_Manager; Cache_Values : ADO.Caches.Cache_Manager_Access; Queries : ADO.Queries.Query_Manager_Access; end record; -- Initialize the sequence factory associated with the session factory. procedure Initialize_Sequences (Factory : in out Session_Factory); end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences; with ADO.Caches; with ADO.Sessions.Sources; -- == Session Factory == -- The session factory is the entry point to obtain a database session. -- The `ADO.Sessions.Factory` package defines the factory for creating -- sessions. -- -- with ADO.Sessions.Factory; -- ... -- Sess_Factory : ADO.Sessions.Factory; -- -- The session factory can be initialized by using the `Create` operation and -- by giving a URI string that identifies the driver and the information to connect -- to the database. The session factory is created only once when the application starts. -- -- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test"); -- -- Having a session factory, one can get a database by using the `Get_Session` or -- `Get_Master_Session` function. Each time this operation is called, a new session -- is returned. The session is released when the session variable is finalized. -- -- DB : ADO.Sessions.Session := Sess_Factory.Get_Session; -- -- The session factory is also responsible for maintaining some data that is shared by -- all the database connections. This includes: -- -- * the sequence generators used to allocate unique identifiers for database tables, -- * the entity cache, -- * some application specific global cache. -- package ADO.Sessions.Factory is pragma Elaborate_Body; ENTITY_CACHE_NAME : constant String := "entity_type"; -- ------------------------------ -- Session factory -- ------------------------------ type Session_Factory is tagged limited private; type Session_Factory_Access is access all Session_Factory'Class; -- Get a read-only session from the factory. function Get_Session (Factory : in Session_Factory) return Session; -- Get a read-write session from the factory. function Get_Master_Session (Factory : in Session_Factory) return Master_Session; -- Open a session procedure Open_Session (Factory : in out Session_Factory; Database : out Session); -- Open a session procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session); -- Create the session factory to connect to the database represented -- by the data source. procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source); -- Create the session factory to connect to the database identified -- by the URI. procedure Create (Factory : out Session_Factory; URI : in String); -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. function Get_Session (Proxy : in Session_Record_Access) return Session; private -- The session factory holds the necessary information to obtain a master or slave -- database connection. The sequence factory is shared by all sessions of the same -- factory (implementation is thread-safe). The factory also contains the entity type -- cache which is initialized when the factory is created. type Session_Factory is tagged limited record Source : ADO.Sessions.Sources.Data_Source; Sequences : Factory_Access := null; Seq_Factory : aliased ADO.Sequences.Factory; -- Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache; Entities : ADO.Sessions.Entity_Cache_Access := null; Cache : aliased ADO.Caches.Cache_Manager; Cache_Values : ADO.Caches.Cache_Manager_Access; Queries : aliased ADO.Queries.Query_Manager; end record; -- Initialize the sequence factory associated with the session factory. procedure Initialize_Sequences (Factory : in out Session_Factory); end ADO.Sessions.Factory;
Replace the Query_Manager_Access by a Query_Manager
Replace the Query_Manager_Access by a Query_Manager
Ada
apache-2.0
stcarrez/ada-ado
622d24332a4b32fba0f69c84890083a7a9ce73cc
src/drivers/ado-drivers.adb
src/drivers/ado-drivers.adb
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.IO_Exceptions; package body ADO.Drivers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers"); -- Global configuration properties (loaded by Initialize). Global_Config : Util.Properties.Manager; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin Log.Info ("Initialize using property file {0}", Config); begin Util.Properties.Load_Properties (Global_Config, Config); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Configuration file '{0}' does not exist", Config); end; Initialize (Global_Config); end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin Global_Config := Util.Properties.Manager (Config); -- Initialize the drivers. ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- Get the global configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Name : in String; Default : in String := "") return String is begin return Global_Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Returns true if the global configuration property is set to true/on. -- ------------------------------ function Is_On (Name : in String) return Boolean is Value : constant String := Global_Config.Get (Name, ""); begin return Value = "on" or Value = "true" or Value = "1"; end Is_On; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Configs; package body ADO.Drivers is -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin ADO.Configs.Initialize (Config); ADO.Drivers.Initialize; end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin ADO.Configs.Initialize (Config); -- Initialize the drivers. ADO.Drivers.Initialize; end Initialize; -- Initialize the drivers which are available. procedure Initialize is separate; end ADO.Drivers;
Remove Database_Error, Driver_Index, Get_Config, Is_On to avoid confusion with operations in ADO.Configs package
Remove Database_Error, Driver_Index, Get_Config, Is_On to avoid confusion with operations in ADO.Configs package
Ada
apache-2.0
stcarrez/ada-ado
a56806c9617d089d5df0dd2a1b0b4b22f10bb1e7
src/nanomsg-socket_pools.adb
src/nanomsg-socket_pools.adb
with Nanomsg.Socket; with Interfaces.C; package body Nanomsg.Socket_Pools is procedure Add_Socket (Self : in out Pool_T; Socket : in Nanomsg.Socket.Socket_T) is begin Pool_Container_P.Insert (Self.Pool, Socket.Get_Fd, Socket); end Add_Socket; procedure Remove_Socket (Self : in out Pool_T; Socket : in Nanomsg.Socket.Socket_T) is begin Pool_Container_P.Delete (Self.Pool, Socket.Get_Fd); end Remove_Socket; function Check_Pool (Self : in Pool_T; Send : in Boolean; Receive : in Boolean) return Pool_T is Retval : Pool_T; package C renames Interfaces.C; type Flags_T is mod 2**C.Short'Size with Size => C.Short'Size; nn_pollin : constant Flags_T := 1; nn_pollout : constant Flags_T := 2; type Nn_Poll_T is record Fd : C.Int; Events : C.Short; Revents : C.Short; end record with Convention => C; type Nn_Poll_Array_T is array (1 .. Pool_Container_P.Length (Self.Pool)) of Nn_Poll_T with Convention => C; type Nn_Poll_Array_Access_T is access all Nn_Poll_Array_T with Convention => C; -- int nn_poll (struct nn_pollfd *fds, int nfds, int timeout); function Nn_Poll (Fds : in out Nn_Poll_Array_T; Nfds : C.Int; Timeout : C.Int) return C.Int with Import, Convention => C , External_Name => "nn_poll"; Req : Nn_Poll_Array_T; In_Flags : C.Short := C.Short ((if Send then NN_Pollout else 0) or (if Receive then NN_Pollin else 0)); Out_Flags : C.Short := 0; use type C.Int; begin declare Position : Pool_Container_P.Cursor := Pool_Container_P.First (Self.Pool); begin for Index in Req'Range loop Req (Index) := (Fd => C.Int (Pool_Container_P.Key (Position)), Events => In_Flags, Revents => Out_Flags); end loop; end; if Nn_Poll (Req, Req'Length, 1000) < 0 then raise Nanomsg.Socket.Socket_Exception with "Nn_Poll failed"; end if; for Element of Req loop declare Result : Flags_T := Flags_T (Element.Revents); begin if Send and then Receive then if (Result and (Nn_Pollin or Nn_Pollout)) = (Nn_Pollin or Nn_Pollout) then Pool_Container_P.Insert (Container => Retval.Pool, Key => Integer (Element.Fd), New_Item => Pool_Container_P.Element (Container => Self.Pool, Key => Integer (Element.Fd))); end if; else declare Is_Matched : Boolean := (Result and (if Send then Nn_Pollout else Nn_Pollin)) = (if Send then Nn_Pollout else Nn_Pollin); begin if Is_Matched then Pool_Container_P.Insert (Container => Retval.Pool, Key => Integer (Element.Fd), New_Item => Pool_Container_P.Element (Container => Self.Pool, Key => Integer (Element.Fd))); end if; end ; end if; end; end loop; return Retval; end Check_Pool; function Has_Message (Self : in Pool_T) return Pool_T is begin return Check_Pool (Self, Receive => True, Send => False); end Has_Message; function Ready_To_Send (Self : in Pool_T) return Pool_T is begin return Check_Pool (Self, Receive => False, Send => True); end Ready_To_Send; function Ready_To_Send_Receive (Self : in Pool_T) return Pool_T is begin return Check_Pool (Self, Receive => True, Send => True); end Ready_To_Send_Receive; function Has_Socket (Self : in Pool_T; Socket : in Nanomsg.Socket.Socket_T) return Boolean is (Pool_Container_P.Contains (Self.Pool, Socket.Get_Fd)); end Nanomsg.Socket_Pools;
with Nanomsg.Socket; with Interfaces.C; package body Nanomsg.Socket_Pools is procedure Add_Socket (Self : in out Pool_T; Socket : in Nanomsg.Socket.Socket_T) is begin Pool_Container_P.Insert (Self.Pool, Socket.Get_Fd, Socket); end Add_Socket; procedure Remove_Socket (Self : in out Pool_T; Socket : in Nanomsg.Socket.Socket_T) is begin Pool_Container_P.Delete (Self.Pool, Socket.Get_Fd); end Remove_Socket; function Check_Pool (Self : in Pool_T; Send : in Boolean; Receive : in Boolean) return Pool_T is Retval : Pool_T; package C renames Interfaces.C; type Flags_T is mod 2**C.Short'Size with Size => C.Short'Size; nn_pollin : constant Flags_T := 1; nn_pollout : constant Flags_T := 2; type Nn_Poll_T is record Fd : C.Int; Events : C.Short; Revents : C.Short; end record with Convention => C; type Nn_Poll_Array_T is array (1 .. Pool_Container_P.Length (Self.Pool)) of Nn_Poll_T with Convention => C; type Nn_Poll_Array_Access_T is access all Nn_Poll_Array_T with Convention => C; -- int nn_poll (struct nn_pollfd *fds, int nfds, int timeout); function Nn_Poll (Fds : in out Nn_Poll_Array_T; Nfds : C.Int; Timeout : C.Int) return C.Int with Import, Convention => C , External_Name => "nn_poll"; Req : Nn_Poll_Array_T; In_Flags : C.Short := C.Short ((if Send then NN_Pollout else 0) or (if Receive then NN_Pollin else 0)); Out_Flags : C.Short := 0; Req_Length : Natural := Req'Length; use type C.Int; begin declare Position : Pool_Container_P.Cursor := Pool_Container_P.First (Self.Pool); begin for Index in Req'Range loop Req (Index) := (Fd => C.Int (Pool_Container_P.Key (Position)), Events => In_Flags, Revents => Out_Flags); end loop; end; if Nn_Poll (Req, C.Int (Req_Length), 1000) < 0 then raise Nanomsg.Socket.Socket_Exception with "Nn_Poll failed"; end if; for Element of Req loop declare Result : Flags_T := Flags_T (Element.Revents); begin if Send and then Receive then if (Result and (Nn_Pollin or Nn_Pollout)) = (Nn_Pollin or Nn_Pollout) then Pool_Container_P.Insert (Container => Retval.Pool, Key => Integer (Element.Fd), New_Item => Pool_Container_P.Element (Container => Self.Pool, Key => Integer (Element.Fd))); end if; else declare Is_Matched : Boolean := (Result and (if Send then Nn_Pollout else Nn_Pollin)) = (if Send then Nn_Pollout else Nn_Pollin); begin if Is_Matched then Pool_Container_P.Insert (Container => Retval.Pool, Key => Integer (Element.Fd), New_Item => Pool_Container_P.Element (Container => Self.Pool, Key => Integer (Element.Fd))); end if; end ; end if; end; end loop; return Retval; end Check_Pool; function Has_Message (Self : in Pool_T) return Pool_T is begin return Check_Pool (Self, Receive => True, Send => False); end Has_Message; function Ready_To_Send (Self : in Pool_T) return Pool_T is begin return Check_Pool (Self, Receive => False, Send => True); end Ready_To_Send; function Ready_To_Send_Receive (Self : in Pool_T) return Pool_T is begin return Check_Pool (Self, Receive => True, Send => True); end Ready_To_Send_Receive; function Has_Socket (Self : in Pool_T; Socket : in Nanomsg.Socket.Socket_T) return Boolean is (Pool_Container_P.Contains (Self.Pool, Socket.Get_Fd)); end Nanomsg.Socket_Pools;
Fix undefined behaviour (GNAT GPL warning)
Fix undefined behaviour (GNAT GPL warning)
Ada
mit
landgraf/nanomsg-ada
e5c4b4d2af34735199158ca0741670acf225885a
awa/src/awa-commands.adb
awa/src/awa-commands.adb
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with AWA.Applications.Configs; with Keystore.Passwords.Input; with Keystore.Passwords.Files; with Keystore.Passwords.Unsafe; with Keystore.Passwords.Cmds; package body AWA.Commands is use type Keystore.Passwords.Provider_Access; use type Keystore.Header_Slot_Count_Type; use type Keystore.Passwords.Keys.Key_Provider_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands"); procedure Load_Configuration (Context : in out Context_Type) is begin begin Context.File_Config.Load_Properties (Context.Config_File.all); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read server configuration file '{0}'", Context.Config_File.all); end; if Context.File_Config.Exists (GPG_CRYPT_CONFIG) then Context.GPG.Set_Encrypt_Command (Context.File_Config.Get (GPG_CRYPT_CONFIG)); end if; if Context.File_Config.Exists (GPG_DECRYPT_CONFIG) then Context.GPG.Set_Decrypt_Command (Context.File_Config.Get (GPG_DECRYPT_CONFIG)); end if; if Context.File_Config.Exists (GPG_LIST_CONFIG) then Context.GPG.Set_List_Key_Command (Context.File_Config.Get (GPG_LIST_CONFIG)); end if; Context.Config.Randomize := not Context.Zero; end Load_Configuration; -- ------------------------------ -- Returns True if a keystore is used by the configuration and must be unlocked. -- ------------------------------ function Use_Keystore (Context : in Context_Type) return Boolean is begin if Context.Wallet_File'Length > 0 then return True; end if; return Context.File_Config.Exists ("keystore.path"); end Use_Keystore; -- ------------------------------ -- Open the keystore file using the password password. -- ------------------------------ procedure Open_Keystore (Context : in out Context_Type) is begin Setup_Password_Provider (Context); Setup_Key_Provider (Context); Context.Wallet.Open (Path => Context.Get_Keystore_Path, Data_Path => Context.Data_Path.all, Config => Context.Config, Info => Context.Info); if not Context.No_Password_Opt or else Context.Info.Header_Count = 0 then if Context.Key_Provider /= null then Context.Wallet.Set_Master_Key (Context.Key_Provider.all); end if; if Context.Provider = null then Context.Provider := Keystore.Passwords.Input.Create (-("Enter password: "), False); end if; Context.Wallet.Unlock (Context.Provider.all, Context.Slot); else Context.GPG.Load_Secrets (Context.Wallet); Context.Wallet.Set_Master_Key (Context.GPG); Context.Wallet.Unlock (Context.GPG, Context.Slot); end if; Keystore.Properties.Initialize (Context.Secure_Config, Context.Wallet'Unchecked_Access); AWA.Applications.Configs.Merge (Context.App_Config, Context.File_Config, Context.Secure_Config, ""); end Open_Keystore; -- ------------------------------ -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. -- ------------------------------ procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type) is Path : constant String := AWA.Applications.Configs.Get_Config_Path (Name); begin begin Context.File_Config.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => null; end; if Context.Use_Keystore then Open_Keystore (Context); else Context.App_Config := Context.File_Config; end if; Application.Initialize (Context.App_Config, Context.Factory); end Configure; -- ------------------------------ -- Initialize the commands. -- ------------------------------ overriding procedure Initialize (Context : in out Context_Type) is begin GC.Set_Usage (Config => Context.Command_Config, Usage => "[switchs] command [arguments]", Help => -("akt - tool to store and protect your sensitive data")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Version'Access, Switch => "-V", Long_Switch => "--version", Help => -("Print the version")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Verbose'Access, Switch => "-v", Long_Switch => "--verbose", Help => -("Verbose execution mode")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Debug'Access, Switch => "-vv", Long_Switch => "--debug", Help => -("Enable debug execution")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Dump'Access, Switch => "-vvv", Long_Switch => "--debug-dump", Help => -("Enable debug dump execution")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Zero'Access, Switch => "-z", Long_Switch => "--zero", Help => -("Erase and fill with zeros instead of random values")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Config_File'Access, Switch => "-c:", Long_Switch => "--config=", Argument => "PATH", Help => -("Defines the path for configuration file")); GC.Initialize_Option_Scan (Stop_At_First_Non_Switch => True); -- Driver.Set_Description (-("akt - tool to store and protect your sensitive data")); -- Driver.Set_Usage (-("[-V] [-v] [-vv] [-vvv] [-c path] [-t count] [-z] " & -- "<command> [<args>]" & ASCII.LF & -- "where:" & ASCII.LF & -- " -V Print the tool version" & ASCII.LF & -- " -v Verbose execution mode" & ASCII.LF & -- " -vv Debug execution mode" & ASCII.LF & -- " -vvv Dump execution mode" & ASCII.LF & -- " -c path Defines the path for akt " & -- "global configuration" & ASCII.LF & -- " -t count Number of threads for the " & -- "encryption/decryption process" & ASCII.LF & -- " -z Erase and fill with zeros instead of random values")); -- Driver.Add_Command ("help", -- -("print some help"), -- Help_Command'Access); end Initialize; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Context.Wallet_File'Access, Switch => "-k:", Long_Switch => "--keystore=", Argument => "PATH", Help => -("Defines the path for the keystore file")); GC.Define_Switch (Config => Config, Output => Context.Data_Path'Access, Switch => "-d:", Long_Switch => "--data-path=", Argument => "PATH", Help => -("The directory which contains the keystore data blocks")); GC.Define_Switch (Config => Config, Output => Context.Password_File'Access, Long_Switch => "--passfile=", Argument => "PATH", Help => -("Read the file that contains the password")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Long_Switch => "--passfd=", Argument => "NUM", Help => -("Read the password from the pipe with" & " the given file descriptor")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Long_Switch => "--passsocket=", Help => -("The password is passed within the socket connection")); GC.Define_Switch (Config => Config, Output => Context.Password_Env'Access, Long_Switch => "--passenv=", Argument => "NAME", Help => -("Read the environment variable that contains" & " the password (not safe)")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Switch => "-p:", Long_Switch => "--password=", Help => -("The password is passed within the command line (not safe)")); GC.Define_Switch (Config => Config, Output => Context.Password_Askpass'Access, Long_Switch => "--passask", Help => -("Run the ssh-askpass command to get the password")); GC.Define_Switch (Config => Config, Output => Context.Password_Command'Access, Long_Switch => "--passcmd=", Argument => "COMMAND", Help => -("Run the command to get the password")); GC.Define_Switch (Config => Config, Output => Context.Wallet_Key_File'Access, Long_Switch => "--wallet-key-file=", Argument => "PATH", Help => -("Read the file that contains the wallet keys")); end Setup_Command; procedure Setup_Password_Provider (Context : in out Context_Type) is begin if Context.Password_Askpass then Context.Provider := Keystore.Passwords.Cmds.Create ("ssh-askpass"); elsif Context.Password_Command'Length > 0 then Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all); elsif Context.Password_File'Length > 0 then Context.Provider := Keystore.Passwords.Files.Create (Context.Password_File.all); elsif Context.Password_Command'Length > 0 then Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all); elsif Context.Unsafe_Password'Length > 0 then Context.Provider := Keystore.Passwords.Unsafe.Create (Context.Unsafe_Password.all); else Context.No_Password_Opt := True; end if; Context.Key_Provider := Keystore.Passwords.Keys.Create (Keystore.DEFAULT_WALLET_KEY); end Setup_Password_Provider; procedure Setup_Key_Provider (Context : in out Context_Type) is begin if Context.Wallet_Key_File'Length > 0 then Context.Key_Provider := Keystore.Passwords.Files.Create (Context.Wallet_Key_File.all); end if; end Setup_Key_Provider; -- ------------------------------ -- Get the keystore file path. -- ------------------------------ function Get_Keystore_Path (Context : in out Context_Type) return String is begin if Context.Wallet_File'Length > 0 then Context.First_Arg := 1; return Context.Wallet_File.all; else raise Error with "No keystore path"; end if; end Get_Keystore_Path; overriding procedure Finalize (Context : in out Context_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Keystore.Passwords.Provider'Class, Name => Keystore.Passwords.Provider_Access); begin GC.Free (Context.Command_Config); Free (Context.Provider); end Finalize; end AWA.Commands;
----------------------------------------------------------------------- -- awa-commands -- AWA commands for server or admin tool -- Copyright (C) 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.IO_Exceptions; with Ada.Command_Line; with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with AWA.Applications.Configs; with Keystore.Passwords.Input; with Keystore.Passwords.Files; with Keystore.Passwords.Unsafe; with Keystore.Passwords.Cmds; package body AWA.Commands is use type Keystore.Passwords.Provider_Access; use type Keystore.Header_Slot_Count_Type; use type Keystore.Passwords.Keys.Key_Provider_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands"); procedure Load_Configuration (Context : in out Context_Type; Path : in String) is begin begin Context.File_Config.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot read server configuration file '{0}'", Path); end; if Context.File_Config.Exists (GPG_CRYPT_CONFIG) then Context.GPG.Set_Encrypt_Command (Context.File_Config.Get (GPG_CRYPT_CONFIG)); end if; if Context.File_Config.Exists (GPG_DECRYPT_CONFIG) then Context.GPG.Set_Decrypt_Command (Context.File_Config.Get (GPG_DECRYPT_CONFIG)); end if; if Context.File_Config.Exists (GPG_LIST_CONFIG) then Context.GPG.Set_List_Key_Command (Context.File_Config.Get (GPG_LIST_CONFIG)); end if; Context.Config.Randomize := not Context.Zero; end Load_Configuration; -- ------------------------------ -- Returns True if a keystore is used by the configuration and must be unlocked. -- ------------------------------ function Use_Keystore (Context : in Context_Type) return Boolean is begin if Context.Wallet_File'Length > 0 then return True; end if; return Context.File_Config.Exists ("keystore.path"); end Use_Keystore; -- ------------------------------ -- Open the keystore file using the password password. -- ------------------------------ procedure Open_Keystore (Context : in out Context_Type) is begin Setup_Password_Provider (Context); Setup_Key_Provider (Context); Context.Wallet.Open (Path => Context.Get_Keystore_Path, Data_Path => Context.Data_Path.all, Config => Context.Config, Info => Context.Info); if not Context.No_Password_Opt or else Context.Info.Header_Count = 0 then if Context.Key_Provider /= null then Context.Wallet.Set_Master_Key (Context.Key_Provider.all); end if; if Context.Provider = null then Context.Provider := Keystore.Passwords.Input.Create (-("Enter password: "), False); end if; Context.Wallet.Unlock (Context.Provider.all, Context.Slot); else Context.GPG.Load_Secrets (Context.Wallet); Context.Wallet.Set_Master_Key (Context.GPG); Context.Wallet.Unlock (Context.GPG, Context.Slot); end if; Keystore.Properties.Initialize (Context.Secure_Config, Context.Wallet'Unchecked_Access); AWA.Applications.Configs.Merge (Context.App_Config, Context.File_Config, Context.Secure_Config, ""); end Open_Keystore; -- ------------------------------ -- Configure the application by loading its configuration file and merging it with -- the keystore file if there is one. -- ------------------------------ procedure Configure (Application : in out AWA.Applications.Application'Class; Name : in String; Context : in out Context_Type) is Path : constant String := AWA.Applications.Configs.Get_Config_Path (Name); begin begin Context.File_Config.Load_Properties (Path); exception when Ada.IO_Exceptions.Name_Error => null; end; if Context.Use_Keystore then Open_Keystore (Context); else Context.App_Config := Context.File_Config; end if; Application.Initialize (Context.App_Config, Context.Factory); end Configure; -- ------------------------------ -- Initialize the commands. -- ------------------------------ overriding procedure Initialize (Context : in out Context_Type) is begin GC.Set_Usage (Config => Context.Command_Config, Usage => "[switchs] command [arguments]", Help => -("akt - tool to store and protect your sensitive data")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Version'Access, Switch => "-V", Long_Switch => "--version", Help => -("Print the version")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Verbose'Access, Switch => "-v", Long_Switch => "--verbose", Help => -("Verbose execution mode")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Debug'Access, Switch => "-vv", Long_Switch => "--debug", Help => -("Enable debug execution")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Dump'Access, Switch => "-vvv", Long_Switch => "--debug-dump", Help => -("Enable debug dump execution")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Zero'Access, Switch => "-z", Long_Switch => "--zero", Help => -("Erase and fill with zeros instead of random values")); GC.Define_Switch (Config => Context.Command_Config, Output => Context.Config_File'Access, Switch => "-c:", Long_Switch => "--config=", Argument => "PATH", Help => -("Defines the path for configuration file")); GC.Initialize_Option_Scan (Stop_At_First_Non_Switch => True); -- Driver.Set_Description (-("akt - tool to store and protect your sensitive data")); -- Driver.Set_Usage (-("[-V] [-v] [-vv] [-vvv] [-c path] [-t count] [-z] " & -- "<command> [<args>]" & ASCII.LF & -- "where:" & ASCII.LF & -- " -V Print the tool version" & ASCII.LF & -- " -v Verbose execution mode" & ASCII.LF & -- " -vv Debug execution mode" & ASCII.LF & -- " -vvv Dump execution mode" & ASCII.LF & -- " -c path Defines the path for akt " & -- "global configuration" & ASCII.LF & -- " -t count Number of threads for the " & -- "encryption/decryption process" & ASCII.LF & -- " -z Erase and fill with zeros instead of random values")); -- Driver.Add_Command ("help", -- -("print some help"), -- Help_Command'Access); end Initialize; -- ------------------------------ -- Setup the command before parsing the arguments and executing it. -- ------------------------------ procedure Setup_Command (Config : in out GC.Command_Line_Configuration; Context : in out Context_Type) is begin GC.Define_Switch (Config => Config, Output => Context.Wallet_File'Access, Switch => "-k:", Long_Switch => "--keystore=", Argument => "PATH", Help => -("Defines the path for the keystore file")); GC.Define_Switch (Config => Config, Output => Context.Data_Path'Access, Switch => "-d:", Long_Switch => "--data-path=", Argument => "PATH", Help => -("The directory which contains the keystore data blocks")); GC.Define_Switch (Config => Config, Output => Context.Password_File'Access, Long_Switch => "--passfile=", Argument => "PATH", Help => -("Read the file that contains the password")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Long_Switch => "--passfd=", Argument => "NUM", Help => -("Read the password from the pipe with" & " the given file descriptor")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Long_Switch => "--passsocket=", Help => -("The password is passed within the socket connection")); GC.Define_Switch (Config => Config, Output => Context.Password_Env'Access, Long_Switch => "--passenv=", Argument => "NAME", Help => -("Read the environment variable that contains" & " the password (not safe)")); GC.Define_Switch (Config => Config, Output => Context.Unsafe_Password'Access, Switch => "-p:", Long_Switch => "--password=", Help => -("The password is passed within the command line (not safe)")); GC.Define_Switch (Config => Config, Output => Context.Password_Askpass'Access, Long_Switch => "--passask", Help => -("Run the ssh-askpass command to get the password")); GC.Define_Switch (Config => Config, Output => Context.Password_Command'Access, Long_Switch => "--passcmd=", Argument => "COMMAND", Help => -("Run the command to get the password")); GC.Define_Switch (Config => Config, Output => Context.Wallet_Key_File'Access, Long_Switch => "--wallet-key-file=", Argument => "PATH", Help => -("Read the file that contains the wallet keys")); end Setup_Command; procedure Setup_Password_Provider (Context : in out Context_Type) is begin if Context.Password_Askpass then Context.Provider := Keystore.Passwords.Cmds.Create ("ssh-askpass"); elsif Context.Password_Command'Length > 0 then Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all); elsif Context.Password_File'Length > 0 then Context.Provider := Keystore.Passwords.Files.Create (Context.Password_File.all); elsif Context.Password_Command'Length > 0 then Context.Provider := Keystore.Passwords.Cmds.Create (Context.Password_Command.all); elsif Context.Unsafe_Password'Length > 0 then Context.Provider := Keystore.Passwords.Unsafe.Create (Context.Unsafe_Password.all); else Context.No_Password_Opt := True; end if; Context.Key_Provider := Keystore.Passwords.Keys.Create (Keystore.DEFAULT_WALLET_KEY); end Setup_Password_Provider; procedure Setup_Key_Provider (Context : in out Context_Type) is begin if Context.Wallet_Key_File'Length > 0 then Context.Key_Provider := Keystore.Passwords.Files.Create (Context.Wallet_Key_File.all); end if; end Setup_Key_Provider; -- ------------------------------ -- Get the keystore file path. -- ------------------------------ function Get_Keystore_Path (Context : in out Context_Type) return String is begin if Context.Wallet_File'Length > 0 then Context.First_Arg := 1; return Context.Wallet_File.all; else raise Error with "No keystore path"; end if; end Get_Keystore_Path; procedure Print (Context : in out Context_Type; Ex : in Ada.Exceptions.Exception_Occurrence) is begin Ada.Exceptions.Reraise_Occurrence (Ex); exception when GNAT.Command_Line.Exit_From_Command_Line | GNAT.Command_Line.Invalid_Switch => Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when Keystore.Bad_Password => Log.Error (-("Invalid password to unlock the keystore file")); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when Keystore.No_Key_Slot => Log.Error (-("There is no available key slot to add the password")); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when Keystore.No_Content => Log.Error (-("No content for an item of type wallet")); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when Keystore.Corrupted => Log.Error (-("The keystore file is corrupted: invalid meta data content")); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when Keystore.Invalid_Block => Log.Error (-("The keystore file is corrupted: invalid data block headers or signature")); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when Keystore.Invalid_Signature => Log.Error (-("The keystore file is corrupted: invalid signature")); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when Keystore.Invalid_Storage => Log.Error (-("The keystore file is corrupted: invalid or missing storage file")); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when Keystore.Invalid_Keystore => Log.Error (-("The file is not a keystore")); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when AWA.Commands.Error | Util.Commands.Not_Found => Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when E : Ada.IO_Exceptions.Name_Error => Log.Error (-("Cannot access file: {0}"), Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); when E : others => Log.Error (-("Some internal error occurred"), E); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end Print; overriding procedure Finalize (Context : in out Context_Type) is procedure Free is new Ada.Unchecked_Deallocation (Object => Keystore.Passwords.Provider'Class, Name => Keystore.Passwords.Provider_Access); begin GC.Free (Context.Command_Config); Free (Context.Provider); end Finalize; end AWA.Commands;
Add Print procedure to report an error message depending on an exception
Add Print procedure to report an error message depending on an exception
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
092181b995411086507860a5a53f3763525c8367
src/base/commands/util-commands-drivers.adb
src/base/commands/util-commands-drivers.adb
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- 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. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Get the description associated with the command. -- ------------------------------ function Get_Description (Command : in Command_Type) return String is begin return To_String (Command.Description); end Get_Description; -- ------------------------------ -- Get the name used to register the command. -- ------------------------------ function Get_Name (Command : in Command_Type) return String is begin return To_String (Command.Name); end Get_Name; -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Compute_Size (Position : in Command_Maps.Cursor); procedure Print (Position : in Command_Maps.Cursor); Column : Ada.Text_IO.Positive_Count := 1; procedure Compute_Size (Position : in Command_Maps.Cursor) is Name : constant String := Command_Maps.Key (Position); begin if Column < Name'Length then Column := Name'Length; end if; end Compute_Size; procedure Print (Position : in Command_Maps.Cursor) is Cmd : constant Command_Access := Command_Maps.Element (Position); Name : constant String := Command_Maps.Key (Position); begin Put (" "); Put (Name); if Length (Cmd.Description) > 0 then Set_Col (Column + 7); Put (To_String (Cmd.Description)); end if; New_Line; end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args, Context); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Compute_Size'Access); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command '{0}'", Cmd_Name); raise Not_Found; else Target_Cmd.Help (Cmd_Name, Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Help_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put ("Invalid command"); end if; end; else Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Name, Command); end Add_Command; procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Description := Ada.Strings.Unbounded.To_Unbounded_String (Description); Add_Command (Driver, Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler) is Command : constant Command_Access := new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Description => To_Unbounded_String (Description), Name => To_Unbounded_String (Name), Handler => Handler); begin Driver.List.Include (Name, Command); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Pos : constant Command_Maps.Cursor := Driver.List.Find (Name); begin if Command_Maps.Has_Element (Pos) then return Command_Maps.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error ("Unkown command '{0}'", Name); raise Not_Found; end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in out Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Handler_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- 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. ----------------------------------------------------------------------- with Util.Log.Loggers; with Ada.Text_IO; use Ada.Text_IO; package body Util.Commands.Drivers is use Ada.Strings.Unbounded; -- The logger Logs : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create (Driver_Name); -- ------------------------------ -- Get the description associated with the command. -- ------------------------------ function Get_Description (Command : in Command_Type) return String is begin return To_String (Command.Description); end Get_Description; -- ------------------------------ -- Get the name used to register the command. -- ------------------------------ function Get_Name (Command : in Command_Type) return String is begin return To_String (Command.Name); end Get_Name; -- ------------------------------ -- Write the command usage. -- ------------------------------ procedure Usage (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is Config : Config_Type; begin Command_Type'Class (Command).Setup (Config, Context); Config_Parser.Usage (Name, Config); end Usage; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. -- ------------------------------ procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is begin Command.Driver.Log (Level, Name, Message); end Log; -- ------------------------------ -- Execute the help command with the arguments. -- Print the help for every registered command. -- ------------------------------ overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Compute_Size (Position : in Command_Sets.Cursor); procedure Print (Position : in Command_Sets.Cursor); Column : Ada.Text_IO.Positive_Count := 1; procedure Compute_Size (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); Len : constant Natural := Length (Cmd.Name); begin if Natural (Column) < Len then Column := Ada.Text_IO.Positive_Count (Len); end if; end Compute_Size; procedure Print (Position : in Command_Sets.Cursor) is Cmd : constant Command_Access := Command_Sets.Element (Position); begin Put (" "); Put (To_String (Cmd.Name)); if Length (Cmd.Description) > 0 then Set_Col (Column + 7); Put (To_String (Cmd.Description)); end if; New_Line; end Print; begin Logs.Debug ("Execute command {0}", Name); if Args.Get_Count = 0 then Usage (Command.Driver.all, Args, Context); New_Line; Put ("Type '"); Put (Args.Get_Command_Name); Put_Line (" help {command}' for help on a specific command."); New_Line; Put_Line ("Available subcommands:"); Command.Driver.List.Iterate (Process => Compute_Size'Access); Command.Driver.List.Iterate (Process => Print'Access); else declare Cmd_Name : constant String := Args.Get_Argument (1); Target_Cmd : constant Command_Access := Command.Driver.Find_Command (Cmd_Name); begin if Target_Cmd = null then Logs.Error ("Unknown command '{0}'", Cmd_Name); raise Not_Found; else Target_Cmd.Help (Cmd_Name, Context); end if; end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Command : in out Help_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; -- ------------------------------ -- Report the command usage. -- ------------------------------ procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Context : in out Context_Type; Name : in String := "") is begin Put_Line (To_String (Driver.Desc)); New_Line; if Name'Length > 0 then declare Command : constant Command_Access := Driver.Find_Command (Name); begin if Command /= null then Command.Usage (Name, Context); else Put ("Invalid command"); end if; end; else Put ("Usage: "); Put (Args.Get_Command_Name); Put (" "); Put_Line (To_String (Driver.Usage)); end if; end Usage; -- ------------------------------ -- Set the driver description printed in the usage. -- ------------------------------ procedure Set_Description (Driver : in out Driver_Type; Description : in String) is begin Driver.Desc := Ada.Strings.Unbounded.To_Unbounded_String (Description); end Set_Description; -- ------------------------------ -- Set the driver usage printed in the usage. -- ------------------------------ procedure Set_Usage (Driver : in out Driver_Type; Usage : in String) is begin Driver.Usage := Ada.Strings.Unbounded.To_Unbounded_String (Usage); end Set_Usage; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Driver := Driver'Unchecked_Access; Driver.List.Include (Command); end Add_Command; procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Command : in Command_Access) is begin Command.Name := To_Unbounded_String (Name); Command.Description := To_Unbounded_String (Description); Add_Command (Driver, Name, Command); end Add_Command; -- ------------------------------ -- Register the command under the given name. -- ------------------------------ procedure Add_Command (Driver : in out Driver_Type; Name : in String; Description : in String; Handler : in Command_Handler) is Command : constant Command_Access := new Handler_Command_Type '(Driver => Driver'Unchecked_Access, Description => To_Unbounded_String (Description), Name => To_Unbounded_String (Name), Handler => Handler); begin Driver.List.Include (Command); end Add_Command; -- ------------------------------ -- Find the command having the given name. -- Returns null if the command was not found. -- ------------------------------ function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access is Cmd : aliased Help_Command_Type; Pos : Command_Sets.Cursor; begin Cmd.Name := To_Unbounded_String (Name); Pos := Driver.List.Find (Cmd'Unchecked_Access); if Command_Sets.Has_Element (Pos) then return Command_Sets.Element (Pos); else return null; end if; end Find_Command; -- ------------------------------ -- Execute the command registered under the given name. -- ------------------------------ procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Execute (Cmd_Args : in Argument_List'Class); Command : constant Command_Access := Driver.Find_Command (Name); procedure Execute (Cmd_Args : in Argument_List'Class) is begin Command.Execute (Name, Cmd_Args, Context); end Execute; begin if Command /= null then declare Config : Config_Type; begin Command.Setup (Config, Context); Config_Parser.Execute (Config, Args, Execute'Access); end; else Logs.Error ("Unkown command '{0}'", Name); raise Not_Found; end if; end Execute; -- ------------------------------ -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- ------------------------------ procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String) is pragma Unreferenced (Driver); begin Logs.Print (Level, "{0}: {1}", Name, Message); end Log; -- ------------------------------ -- Execute the command with the arguments. -- ------------------------------ overriding procedure Execute (Command : in out Handler_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is begin Command.Handler (Name, Args, Context); end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Handler_Command_Type; Name : in String; Context : in out Context_Type) is begin null; end Help; end Util.Commands.Drivers;
Change the implementation to use an Ordered_Set
Change the implementation to use an Ordered_Set
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c73c7ba31fced7422fb3dc054a683f56d50ca796
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; 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;
----------------------------------------------------------------------- -- 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.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 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 unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-security
20605e5965051cc51b4772e3930d16b9b8c7176c
src/os-win32/util-systems-os.ads
src/os-win32/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "GetLastError"); -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is System.Address; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is HANDLE; NO_FILE : constant File_Type := System.Null_Address; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "CloseHandle"); function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := System.Null_Address; hStdOutput : HANDLE := System.Null_Address; hStdError : HANDLE := System.Null_Address; end record; pragma Pack (Startup_Info); type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Windows system operations -- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Windows). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '\'; -- The path separator. Path_Separator : constant Character := ';'; -- Defines several windows specific types. type BOOL is mod 8; type WORD is new Interfaces.C.short; type DWORD is new Interfaces.C.unsigned_long; type PDWORD is access all DWORD; for PDWORD'Size use Standard'Address_Size; function Get_Last_Error return Integer; pragma Import (Stdcall, Get_Last_Error, "GetLastError"); -- Some useful error codes (See Windows document "System Error Codes (0-499)"). ERROR_BROKEN_PIPE : constant Integer := 109; -- ------------------------------ -- Handle -- ------------------------------ -- The windows HANDLE is defined as a void* in the C API. subtype HANDLE is Util.Systems.Types.HANDLE; type PHANDLE is access all HANDLE; for PHANDLE'Size use Standard'Address_Size; function Wait_For_Single_Object (H : in HANDLE; Time : in DWORD) return DWORD; pragma Import (Stdcall, Wait_For_Single_Object, "WaitForSingleObject"); type Security_Attributes is record Length : DWORD; Security_Descriptor : System.Address; Inherit : Boolean; end record; type LPSECURITY_ATTRIBUTES is access all Security_Attributes; for LPSECURITY_ATTRIBUTES'Size use Standard'Address_Size; -- ------------------------------ -- File operations -- ------------------------------ subtype File_Type is Util.Systems.Types.File_Type; NO_FILE : constant File_Type := System.Null_Address; STD_INPUT_HANDLE : constant DWORD := -10; STD_OUTPUT_HANDLE : constant DWORD := -11; STD_ERROR_HANDLE : constant DWORD := -12; function Get_Std_Handle (Kind : in DWORD) return File_Type; pragma Import (Stdcall, Get_Std_Handle, "GetStdHandle"); function STDIN_FILENO return File_Type is (Get_Std_Handle (STD_INPUT_HANDLE)); function Close_Handle (Fd : in File_Type) return BOOL; pragma Import (Stdcall, Close_Handle, "CloseHandle"); function Duplicate_Handle (SourceProcessHandle : in HANDLE; SourceHandle : in HANDLE; TargetProcessHandle : in HANDLE; TargetHandle : in PHANDLE; DesiredAccess : in DWORD; InheritHandle : in BOOL; Options : in DWORD) return BOOL; pragma Import (Stdcall, Duplicate_Handle, "DuplicateHandle"); function Read_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Read_File, "ReadFile"); function Write_File (Fd : in File_Type; Buf : in System.Address; Size : in DWORD; Result : in PDWORD; Overlap : in System.Address) return BOOL; pragma Import (Stdcall, Write_File, "WriteFile"); function Create_Pipe (Read_Handle : in PHANDLE; Write_Handle : in PHANDLE; Attributes : in LPSECURITY_ATTRIBUTES; Buf_Size : in DWORD) return BOOL; pragma Import (Stdcall, Create_Pipe, "CreatePipe"); -- type Size_T is mod 2 ** Standard'Address_Size; subtype LPWSTR is Interfaces.C.Strings.chars_ptr; subtype PBYTE is Interfaces.C.Strings.chars_ptr; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype LPCTSTR is System.Address; subtype LPTSTR is System.Address; type CommandPtr is access all Interfaces.C.wchar_array; NULL_STR : constant LPWSTR := Interfaces.C.Strings.Null_Ptr; type Startup_Info is record cb : DWORD := 0; lpReserved : LPWSTR := NULL_STR; lpDesktop : LPWSTR := NULL_STR; lpTitle : LPWSTR := NULL_STR; dwX : DWORD := 0; dwY : DWORD := 0; dwXsize : DWORD := 0; dwYsize : DWORD := 0; dwXCountChars : DWORD := 0; dwYCountChars : DWORD := 0; dwFillAttribute : DWORD := 0; dwFlags : DWORD := 0; wShowWindow : WORD := 0; cbReserved2 : WORD := 0; lpReserved2 : PBYTE := Interfaces.C.Strings.Null_Ptr; hStdInput : HANDLE := System.Null_Address; hStdOutput : HANDLE := System.Null_Address; hStdError : HANDLE := System.Null_Address; end record; pragma Pack (Startup_Info); type Startup_Info_Access is access all Startup_Info; type PROCESS_INFORMATION is record hProcess : HANDLE := NO_FILE; hThread : HANDLE := NO_FILE; dwProcessId : DWORD; dwThreadId : DWORD; end record; type Process_Information_Access is access all PROCESS_INFORMATION; function Get_Current_Process return HANDLE; pragma Import (Stdcall, Get_Current_Process, "GetCurrentProcess"); function Get_Exit_Code_Process (Proc : in HANDLE; Code : in PDWORD) return BOOL; pragma Import (Stdcall, Get_Exit_Code_Process, "GetExitCodeProcess"); function Create_Process (Name : in LPCTSTR; Command : in System.Address; Process_Attributes : in LPSECURITY_ATTRIBUTES; Thread_Attributes : in LPSECURITY_ATTRIBUTES; Inherit_Handlers : in Boolean; Creation_Flags : in DWORD; Environment : in LPTSTR; Directory : in LPCTSTR; Startup_Info : in Startup_Info_Access; Process_Info : in Process_Information_Access) return Integer; pragma Import (Stdcall, Create_Process, "CreateProcessW"); -- Terminate the windows process and all its threads. function Terminate_Process (Proc : in HANDLE; Code : in DWORD) return Integer; pragma Import (Stdcall, Terminate_Process, "TerminateProcess"); function Sys_Stat (Path : in LPWSTR; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, "_stat64"); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, "_fstat64"); private -- kernel32 is used on Windows32 as well as Windows64. pragma Linker_Options ("-lkernel32"); end Util.Systems.Os;
Use types declared in Util.Systems.Types Declare STDIN_FILENO
Use types declared in Util.Systems.Types Declare STDIN_FILENO
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
080b2198b50b7a92b0ee12fac6167fe3cc397c01
src/security-controllers.ads
src/security-controllers.ads
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
Add the permission to the Has_Permission function so that some permissions could specify a resource (ie, File_Permission, URL_Permission, ...)
Add the permission to the Has_Permission function so that some permissions could specify a resource (ie, File_Permission, URL_Permission, ...)
Ada
apache-2.0
Letractively/ada-security
a6ffb57673b7d9910eb50d4939d8973f0b2259b6
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; limited with Security.Controllers; limited with Security.Contexts; -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- package Security.Permissions is Invalid_Name : exception; type Security_Context_Access is access all Contexts.Security_Context'Class; type Permission_Index is new Natural; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission is abstract tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; private use Util.Strings; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission is abstract tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
Remove the with clauses which are no longer necessary
Remove the with clauses which are no longer necessary
Ada
apache-2.0
Letractively/ada-security
dbe1c4dea5d487e5d286e831c4e818f487593b92
src/sys/processes/os-linux/util-systems-os.ads
src/sys/processes/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-systems-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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; 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 => "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 => "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 => "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 => "_exit"; -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => "fork"; -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => "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 => "execvp"; -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer with Import => True, Convention => C, Link_Name => "waitpid"; -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer with Import => True, Convention => C, Link_Name => "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 => "dup2"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => "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 => "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 => "fcntl"; function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer with Import => True, Convention => C, Link_Name => "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 => "lseek"; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => "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 => "chmod"; -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer with Import => True, Convention => C, Link_Name => "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 => "rename"; -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer with Import => True, Convention => C, Link_Name => "__get_errno"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => C, Link_Name => "strerror"; end Util.Systems.Os;
----------------------------------------------------------------------- -- util-systems-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with 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; 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 => "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 => "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 => "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 => "_exit"; -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => "fork"; -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier with Import => True, Convention => C, Link_Name => "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 => "execvp"; -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer with Import => True, Convention => C, Link_Name => "waitpid"; -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer with Import => True, Convention => C, Link_Name => "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 => "dup2"; -- Close a file function Sys_Close (Fd : in File_Type) return Integer with Import => True, Convention => C, Link_Name => "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 => "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 => "fcntl"; function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer with Import => True, Convention => C, Link_Name => "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 => "lseek"; function Sys_Ftruncate (Fs : in File_Type; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => "ftruncate"; function Sys_Truncate (Path : in Ptr; Length : in Util.Systems.Types.off_t) return Integer with Import => True, Convention => C, Link_Name => "truncate"; function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer with Import => True, Convention => C, Link_Name => "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 => "chmod"; -- Change working directory. function Sys_Chdir (Path : in Ptr) return Integer with Import => True, Convention => C, Link_Name => "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 => "rename"; -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer with Import => True, Convention => C, Link_Name => "__get_errno"; function Strerror (Errno : in Integer) return Interfaces.C.Strings.chars_ptr with Import => True, Convention => C, Link_Name => "strerror"; end Util.Systems.Os;
Declare Sys_Truncate and Sys_Ftruncate to get access to ftruncate(2) and truncate(2)
Declare Sys_Truncate and Sys_Ftruncate to get access to ftruncate(2) and truncate(2)
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a0b63c4cc21c80e8cacf66316553a8df3fc5b84b
regtests/asf-servlets-tests.ads
regtests/asf-servlets-tests.ads
----------------------------------------------------------------------- -- Servlets Tests - Unit tests for ASF.Servlets -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Servlets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test_Servlet1 is new Servlet with null record; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test_Servlet2 is new Test_Servlet1 with null record; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test is new Util.Tests.Test with record Writer : Integer; end record; -- Test creation of session procedure Test_Create_Servlet (T : in out Test); -- Test add servlet procedure Test_Add_Servlet (T : in out Test); -- Test getting a resource path procedure Test_Get_Resource (T : in out Test); procedure Test_Request_Dispatcher (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Servlet_Path (T : in out Test); -- Check that the mapping for the given URI matches the server. procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access); -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String); end ASF.Servlets.Tests;
----------------------------------------------------------------------- -- Servlets Tests - Unit tests for ASF.Servlets -- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Servlets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test_Servlet1 is new Servlet with null record; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test_Servlet2 is new Test_Servlet1 with null record; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test is new Util.Tests.Test with record Writer : Integer; end record; -- Test creation of session procedure Test_Create_Servlet (T : in out Test); -- Test add servlet procedure Test_Add_Servlet (T : in out Test); -- Test getting a resource path procedure Test_Get_Resource (T : in out Test); procedure Test_Request_Dispatcher (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Servlet_Path (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Filter_Mapping (T : in out Test); -- Check that the mapping for the given URI matches the server. procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access; Filter : in Natural := 0); -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String); end ASF.Servlets.Tests;
Declare the Test_Filter_Mapping procedure to test the filter mapping
Declare the Test_Filter_Mapping procedure to test the filter mapping
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f5c929c9c96e86f5d19fce3aa0f6a037b4f2e190
regtests/asf-servlets-tests.ads
regtests/asf-servlets-tests.ads
----------------------------------------------------------------------- -- Servlets Tests - Unit tests for ASF.Servlets -- 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.Tests; package ASF.Servlets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test_Servlet1 is new Servlet with null record; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test_Servlet2 is new Test_Servlet1 with null record; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test is new Util.Tests.Test with record Writer : Integer; end record; -- Test creation of session procedure Test_Create_Servlet (T : in out Test); -- Test add servlet procedure Test_Add_Servlet (T : in out Test); -- Test getting a resource path procedure Test_Get_Resource (T : in out Test); procedure Test_Request_Dispatcher (T : in out Test); -- Check that the mapping for the given URI matches the server. procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access); end ASF.Servlets.Tests;
----------------------------------------------------------------------- -- Servlets Tests - Unit tests for ASF.Servlets -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ASF.Servlets.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test_Servlet1 is new Servlet with null record; procedure Do_Get (Server : in Test_Servlet1; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test_Servlet2 is new Test_Servlet1 with null record; procedure Do_Post (Server : in Test_Servlet2; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); type Test is new Util.Tests.Test with record Writer : Integer; end record; -- Test creation of session procedure Test_Create_Servlet (T : in out Test); -- Test add servlet procedure Test_Add_Servlet (T : in out Test); -- Test getting a resource path procedure Test_Get_Resource (T : in out Test); procedure Test_Request_Dispatcher (T : in out Test); -- Test mapping and servlet path on a request. procedure Test_Servlet_Path (T : in out Test); -- Check that the mapping for the given URI matches the server. procedure Check_Mapping (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Server : in Servlet_Access); -- Check that the request is done on the good servlet and with the correct servlet path -- and path info. procedure Check_Request (T : in out Test; Ctx : in Servlet_Registry; URI : in String; Servlet_Path : in String; Path_Info : in String); end ASF.Servlets.Tests;
Add a unit test to check the request servlet path
Add a unit test to check the request servlet path
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
2dfa35b61cb51fbe3a8a8942af94ace8e97a1d4b
src/postgresql/ado-drivers-connections-postgresql.adb
src/postgresql/ado-drivers-connections-postgresql.adb
----------------------------------------------------------------------- -- ADO Postgresql Database -- Postgresql Database connections -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Postgresql; with ADO.Schemas.Postgresql; with ADO.Sessions; with ADO.C; package body ADO.Drivers.Connections.Postgresql is use ADO.Statements.Postgresql; use Interfaces.C; use type PQ.PGconn_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Postgresql"); Driver_Name : aliased constant String := "postgresql"; Driver : aliased Postgresql_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 Database.Execute ("BEGIN"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin Database.Execute ("COMMIT"); end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin Database.Execute ("ROLLBACK"); end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Postgresql.Load_Schema (Database, Schema, Ada.Strings.Unbounded.To_String (Database.Name)); 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 : PQ.PGresult_Access; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = PQ.Null_PGconn then Log.Error ("Database connection is not open"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := PQ.PQexec (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", PQ.ExecStatusType'Image (PQ.PQresultStatus (Result))); PQ.PQclear (Result); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= PQ.Null_PGconn then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); PQ.PQfinish (Database.Server); Database.Server := PQ.Null_PGconn; end if; end Close; -- ------------------------------ -- Releases the Postgresql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- Postgresql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Postgresql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is use type PQ.ConnStatusType; URI : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.URI); Connection : PQ.PGconn_Access; begin Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), To_String (Config.Server), To_String (Config.Database)); if Config.Get_Property ("password") = "" then Log.Debug ("Postgresql connection with user={0}", Config.Get_Property ("user")); else Log.Debug ("Postgresql connection with user={0} password=XXXXXXXX", Config.Get_Property ("user")); end if; Connection := PQ.PQconnectdb (ADO.C.To_C (URI)); if Connection = PQ.Null_PGconn then declare Message : constant String := "memory allocation error"; begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.Log_URI), Message); raise Connection_Error with "Cannot connect to Postgresql server: " & Message; end; end if; if PQ.PQstatus (Connection) /= PQ.CONNECTION_OK then declare Message : constant String := Strings.Value (PQ.PQerrorMessage (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", To_String (Config.Log_URI), Message); raise Connection_Error with "Cannot connect to Postgresql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Connection; Database.Name := Config.Database; Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the Postgresql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing Postgresql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Postgresql driver. -- ------------------------------ overriding procedure Finalize (D : in out Postgresql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the Postgresql driver"); end Finalize; end ADO.Drivers.Connections.Postgresql;
----------------------------------------------------------------------- -- ADO Postgresql Database -- Postgresql Database connections -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Identification; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with Util.Processes.Tools; with ADO.Statements.Postgresql; with ADO.Schemas.Postgresql; with ADO.Sessions; with ADO.C; package body ADO.Drivers.Connections.Postgresql is use ADO.Statements.Postgresql; use Interfaces.C; use type PQ.PGconn_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Postgresql"); Driver_Name : aliased constant String := "postgresql"; Driver : aliased Postgresql_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 Database.Execute ("BEGIN"); end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin Database.Execute ("COMMIT"); end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin Database.Execute ("ROLLBACK"); end Rollback; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Postgresql.Load_Schema (Database, Schema, Ada.Strings.Unbounded.To_String (Database.Name)); end Load_Schema; -- ------------------------------ -- Create the database and initialize it with the schema SQL file. -- ------------------------------ overriding procedure Create_Database (Database : in Database_Connection; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is pragma Unreferenced (Database); Status : Integer; Command : constant String := "psql -q '" & Config.Get_URI & "' --file=" & Schema_Path; begin Util.Processes.Tools.Execute (Command, Messages, Status); if Status = 0 then Log.Info ("Database schema created successfully."); elsif Status = 255 then Log.Error ("Command not found: {0}", Command); else Log.Error ("Command {0} failed with exit code {1}", Command, Util.Strings.Image (Status)); end if; end Create_Database; -- ------------------------------ -- 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 : PQ.PGresult_Access; begin Log.Debug ("Execute SQL: {0}", SQL); if Database.Server = PQ.Null_PGconn then Log.Error ("Database connection is not open"); raise ADO.Sessions.Session_Error with "Database connection is closed"; end if; Result := PQ.PQexec (Database.Server, ADO.C.To_C (SQL_Stat)); Log.Debug ("Query result: {0}", PQ.ExecStatusType'Image (PQ.PQresultStatus (Result))); PQ.PQclear (Result); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is begin if Database.Server /= PQ.Null_PGconn then Log.Info ("Closing connection {0}/{1}", Database.Name, Database.Ident); PQ.PQfinish (Database.Server); Database.Server := PQ.Null_PGconn; end if; end Close; -- ------------------------------ -- Releases the Postgresql connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is begin Log.Debug ("Release connection {0}/{1}", Database.Name, Database.Ident); Database.Close; end Finalize; -- ------------------------------ -- Initialize the database connection manager. -- -- Postgresql://localhost:3306/db -- -- ------------------------------ procedure Create_Connection (D : in out Postgresql_Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is use type PQ.ConnStatusType; URI : constant ADO.C.String_Ptr := ADO.C.To_String_Ptr (Config.Get_URI); Connection : PQ.PGconn_Access; begin Log.Info ("Task {0} connecting to {1}:{2}", Ada.Task_Identification.Image (Ada.Task_Identification.Current_Task), Config.Get_Server, Config.Get_Database); if Config.Get_Property ("password") = "" then Log.Debug ("Postgresql connection with user={0}", Config.Get_Property ("user")); else Log.Debug ("Postgresql connection with user={0} password=XXXXXXXX", Config.Get_Property ("user")); end if; Connection := PQ.PQconnectdb (ADO.C.To_C (URI)); if Connection = PQ.Null_PGconn then declare Message : constant String := "memory allocation error"; begin Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message); raise ADO.Configs.Connection_Error with "Cannot connect to Postgresql server: " & Message; end; end if; if PQ.PQstatus (Connection) /= PQ.CONNECTION_OK then declare Message : constant String := Strings.Value (PQ.PQerrorMessage (Connection)); begin Log.Error ("Cannot connect to '{0}': {1}", Config.Get_Log_URI, Message); raise ADO.Configs.Connection_Error with "Cannot connect to Postgresql server: " & Message; end; end if; D.Id := D.Id + 1; declare Ident : constant String := Util.Strings.Image (D.Id); Database : constant Database_Connection_Access := new Database_Connection; begin Database.Ident (1 .. Ident'Length) := Ident; Database.Server := Connection; Database.Name := To_Unbounded_String (Config.Get_Database); Result := Ref.Create (Database.all'Access); end; end Create_Connection; -- ------------------------------ -- Initialize the Postgresql driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing Postgresql driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; -- ------------------------------ -- Deletes the Postgresql driver. -- ------------------------------ overriding procedure Finalize (D : in out Postgresql_Driver) is pragma Unreferenced (D); begin Log.Debug ("Deleting the Postgresql driver"); end Finalize; end ADO.Drivers.Connections.Postgresql;
Implement the Create_Database and update Create_Connection after changes in ADO.Configs
Implement the Create_Database and update Create_Connection after changes in ADO.Configs
Ada
apache-2.0
stcarrez/ada-ado
04a7b8977e2d02a6757ded744e56979e1771739c
src/gen-model-mappings.adb
src/gen-model-mappings.adb
----------------------------------------------------------------------- -- 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 Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- Mapping Definition -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if Mapping_Maps.Has_Element (Pos) then return Mapping_Maps.Element (Pos); else Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); if Mapping_Maps.Has_Element (Pos) then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Types.Insert (Name, Mapping); end if; Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
----------------------------------------------------------------------- -- gen-model-mappings -- Type mappings for Code Generator -- Copyright (C) 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; -- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML -- type into the Ada type. package body Gen.Model.Mappings is use Ada.Strings.Unbounded; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.Mappings"); Types : Mapping_Maps.Map; Mapping_Name : Unbounded_String; -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Mapping_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "name" then return Util.Beans.Objects.To_Object (From.Target); elsif Name = "isBoolean" then return Util.Beans.Objects.To_Object (From.Kind = T_BOOLEAN); elsif Name = "isInteger" then return Util.Beans.Objects.To_Object (From.Kind = T_INTEGER); elsif Name = "isString" then return Util.Beans.Objects.To_Object (From.Kind = T_STRING); elsif Name = "isIdentifier" then return Util.Beans.Objects.To_Object (From.Kind = T_IDENTIFIER); elsif Name = "isDate" then return Util.Beans.Objects.To_Object (From.Kind = T_DATE); elsif Name = "isBlob" then return Util.Beans.Objects.To_Object (From.Kind = T_BLOB); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (From.Kind = T_ENUM); elsif Name = "isPrimitiveType" then return Util.Beans.Objects.To_Object (From.Kind /= T_TABLE and From.Kind /= T_BLOB); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Find the mapping for the given type name. -- ------------------------------ function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String; Allow_Null : in Boolean) return Mapping_Definition_Access is Pos : constant Mapping_Maps.Cursor := Types.Find (Mapping_Name & Name); begin if not Mapping_Maps.Has_Element (Pos) then Log.Info ("Type '{0}' not found in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return null; elsif Allow_Null then if Mapping_Maps.Element (Pos).Allow_Null = null then Log.Info ("Type '{0}' does not allow a null value in mapping table '{1}'", To_String (Name), To_String (Mapping_Name)); return Mapping_Maps.Element (Pos); end if; return Mapping_Maps.Element (Pos).Allow_Null; else return Mapping_Maps.Element (Pos); end if; end Find_Type; procedure Register_Type (Name : in String; Mapping : in Mapping_Definition_Access; Kind : in Basic_Type) is N : constant Unbounded_String := Mapping_Name & To_Unbounded_String (Name); Pos : constant Mapping_Maps.Cursor := Types.Find (N); begin Log.Debug ("Register type '{0}'", Name); if not Mapping_Maps.Has_Element (Pos) then Mapping.Kind := Kind; Types.Insert (N, Mapping); end if; end Register_Type; -- ------------------------------ -- Register a type mapping <b>From</b> that is mapped to <b>Target</b>. -- ------------------------------ procedure Register_Type (Target : in String; From : in String; Kind : in Basic_Type; Allow_Null : in Boolean) is Name : constant Unbounded_String := Mapping_Name & To_Unbounded_String (From); Pos : constant Mapping_Maps.Cursor := Types.Find (Name); Mapping : Mapping_Definition_Access; Found : Boolean; begin Log.Debug ("Register type '{0}' mapped to '{1}' type {2}", From, Target, Basic_Type'Image (Kind)); Found := Mapping_Maps.Has_Element (Pos); if Found then Mapping := Mapping_Maps.Element (Pos); else Mapping := new Mapping_Definition; Types.Insert (Name, Mapping); end if; if Allow_Null then Mapping.Allow_Null := new Mapping_Definition; Mapping.Allow_Null.Target := To_Unbounded_String (Target); Mapping.Allow_Null.Kind := Kind; if not Found then Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; else Mapping.Target := To_Unbounded_String (Target); Mapping.Kind := Kind; end if; end Register_Type; -- ------------------------------ -- Setup the type mapping for the language identified by the given name. -- ------------------------------ procedure Set_Mapping_Name (Name : in String) is begin Log.Info ("Using type mapping {0}", Name); Mapping_Name := To_Unbounded_String (Name & "."); end Set_Mapping_Name; end Gen.Model.Mappings;
Update Register_Type and Find_Type to record and return a specific mapping type when the type must support null values
Update Register_Type and Find_Type to record and return a specific mapping type when the type must support null values
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
6b2e3a8e9276050f46a5425823a8ed39f3747f91
tools/druss-config.ads
tools/druss-config.ads
----------------------------------------------------------------------- -- druss-config -- Configuration management for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with Druss.Gateways; package Druss.Config is -- Initialize the configuration. procedure Initialize; -- Get the configuration parameter. function Get (Name : in String) return String; -- Initalize the list of gateways from the configuration file. procedure Get_Gateways (List : in out Druss.Gateways.Gateway_Vector); end Druss.Config;
----------------------------------------------------------------------- -- druss-config -- Configuration management for Druss -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Druss.Gateways; package Druss.Config is -- Initialize the configuration. procedure Initialize (Path : in String); -- Get the configuration parameter. function Get (Name : in String) return String; -- Initalize the list of gateways from the configuration file. procedure Get_Gateways (List : in out Druss.Gateways.Gateway_Vector); end Druss.Config;
Add a Path parameter to the Initialize procedure
Add a Path parameter to the Initialize procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
4e7cbfc918f37d719ef910ac9a0b79e65c6224a6
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 -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.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 thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Types.Tick_Image (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String) is begin Console_Type'Class (Console).Print_Field (Field, Ada.Strings.Unbounded.To_String (Value)); end Print_Field; 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 -- ------------------------------ -- Print the title for the given field and setup the associated field size. -- ------------------------------ procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive) is begin Console.Sizes (Field) := Length; if Console.Field_Count >= 1 then Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count)) + Console.Sizes (Console.Fields (Console.Field_Count)); else Console.Cols (Field) := 1; end if; Console.Field_Count := Console.Field_Count + 1; Console.Fields (Console.Field_Count) := Field; Console_Type'Class (Console).Print_Title (Field, Title); end Print_Title; -- ------------------------------ -- Format the address and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr) is Value : constant String := MAT.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 thread information and print it for the given field. -- ------------------------------ procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref) is Value : constant String := MAT.Types.Target_Thread_Ref'Image (Thread); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Thread; -- ------------------------------ -- Format the time tick as a duration and print it for the given field. -- ------------------------------ procedure Print_Duration (Console : in out Console_Type; Field : in Field_Type; Duration : in MAT.Types.Target_Tick_Ref) is Value : constant String := MAT.Types.Tick_Image (Duration); begin Console_Type'Class (Console).Print_Field (Field, Value); end Print_Duration; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer; Justify : in Justify_Type := J_LEFT) is Val : constant String := Integer'Image (Value); begin Console_Type'Class (Console).Print_Field (Field, Val, Justify); end Print_Field; -- ------------------------------ -- Format the integer and print it for the given field. -- ------------------------------ procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String; Justify : in Justify_Type := J_LEFT) is Item : String := Ada.Strings.Unbounded.To_String (Value); Size : constant Natural := Console.Sizes (Field); begin if Size <= Item'Length then Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "..."; Console_Type'Class (Console).Print_Field (Field, Item (Item'Last - Size + 2 .. Item'Last)); else Console_Type'Class (Console).Print_Field (Field, Item, Justify); end if; end Print_Field; end MAT.Consoles;
Add and handle the Justify parameter to the Print_Field procedure
Add and handle the Justify parameter to the Print_Field procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c436b68baa387ca0069e1e080885796264e02657
src/security-oauth-jwt.adb
src/security-oauth-jwt.adb
----------------------------------------------------------------------- -- security-oauth-jwt -- OAuth Java Web Token -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Conversions; with Interfaces.C; with Util.Encoders; with Util.Strings; with Util.Serialize.IO; with Util.Properties.JSON; with Util.Log.Loggers; package body Security.OAuth.JWT is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.JWT"); function Get_Time (From : in Util.Properties.Manager; Name : in String) return Ada.Calendar.Time; -- Decode the part using base64url and parse the JSON content into the property manager. procedure Decode_Part (Into : in out Util.Properties.Manager; Name : in String; Data : in String); function Get_Time (From : in Util.Properties.Manager; Name : in String) return Ada.Calendar.Time is Value : constant String := From.Get (Name); begin return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (Value)); end Get_Time; -- ------------------------------ -- Get the issuer claim from the token (the "iss" claim). -- ------------------------------ function Get_Issuer (From : in Token) return String is begin return From.Claims.Get ("iss"); end Get_Issuer; -- ------------------------------ -- Get the subject claim from the token (the "sub" claim). -- ------------------------------ function Get_Subject (From : in Token) return String is begin return From.Claims.Get ("sub"); end Get_Subject; -- ------------------------------ -- Get the audience claim from the token (the "aud" claim). -- ------------------------------ function Get_Audience (From : in Token) return String is begin return From.Claims.Get ("aud"); end Get_Audience; -- ------------------------------ -- Get the expiration claim from the token (the "exp" claim). -- ------------------------------ function Get_Expiration (From : in Token) return Ada.Calendar.Time is begin return Get_Time (From.Claims, "exp"); end Get_Expiration; -- ------------------------------ -- Get the not before claim from the token (the "nbf" claim). -- ------------------------------ function Get_Not_Before (From : in Token) return Ada.Calendar.Time is begin return Get_Time (From.Claims, "nbf"); end Get_Not_Before; -- ------------------------------ -- Get the issued at claim from the token (the "iat" claim). -- ------------------------------ function Get_Issued_At (From : in Token) return Ada.Calendar.Time is begin return Get_Time (From.Claims, "iat"); end Get_Issued_At; -- ------------------------------ -- Get the authentication time claim from the token (the "auth_time" claim). -- ------------------------------ function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time is begin return Get_Time (From.Claims, "auth_time"); end Get_Authentication_Time; -- ------------------------------ -- Get the JWT ID claim from the token (the "jti" claim). -- ------------------------------ function Get_JWT_ID (From : in Token) return String is begin return From.Claims.Get ("jti"); end Get_JWT_ID; -- ------------------------------ -- Get the authorized clients claim from the token (the "azp" claim). -- ------------------------------ function Get_Authorized_Presenters (From : in Token) return String is begin return From.Claims.Get ("azp"); end Get_Authorized_Presenters; -- ------------------------------ -- Get the claim with the given name from the token. -- ------------------------------ function Get_Claim (From : in Token; Name : in String) return String is begin return From.Claims.Get (Name); end Get_Claim; -- ------------------------------ -- Decode the part using base64url and parse the JSON content into the property manager. -- ------------------------------ procedure Decode_Part (Into : in out Util.Properties.Manager; Name : in String; Data : in String) is Decoder : constant Util.Encoders.Encoder := Util.Encoders.Create (Util.Encoders.BASE_64_URL); Content : constant String := Decoder.Decode (Data); begin Log.Debug ("Decoding {0}: {1}", Name, Content); Util.Properties.JSON.Parse_JSON (Into, Content); end Decode_Part; -- ------------------------------ -- Decode a string representing an encoded JWT token according to the JWT specification: -- -- Section 7. Rules for Creating and Validating a JWT -- -- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' . -- The first part represents the header, the second part the claims and the last part -- the signature. The <tt>Decode</tt> operation splits the parts, decodes them, -- parses the JSON content represented by the header and the claims. -- The <tt>Decode</tt> operation does not verify the signature (yet!). -- -- Return the decoded token or raise an exception. -- ------------------------------ function Decode (Content : in String) return Token is Pos1 : constant Natural := Util.Strings.Index (Content, '.'); Pos2 : Natural; Result : Token; begin if Pos1 = 0 then Log.Error ("Invalid JWT token: missing '.' separator. JWT: {0}", Content); raise Invalid_Token with "Missing header separator"; end if; Pos2 := Util.Strings.Index (Content, '.', Pos1 + 1); if Pos2 = 0 then Log.Error ("Invalid JWT token: missing second '.' separator. JWT: {0}", Content); raise Invalid_Token with "Missing signature separator"; end if; Decode_Part (Result.Header, "header", Content (Content'First .. Pos1 - 1)); Decode_Part (Result.Claims, "claims", Content (Pos1 + 1 .. Pos2 - 1)); return Result; exception when Util.Serialize.IO.Parse_Error => raise Invalid_Token with "Invalid JSON content"; end Decode; end Security.OAuth.JWT;
----------------------------------------------------------------------- -- security-oauth-jwt -- OAuth Java Web Token -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar.Conversions; with Interfaces.C; with Util.Encoders; with Util.Strings; with Util.Serialize.IO; with Util.Properties.JSON; with Util.Log.Loggers; package body Security.OAuth.JWT is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.JWT"); function Get_Time (From : in Util.Properties.Manager; Name : in String) return Ada.Calendar.Time; -- Decode the part using base64url and parse the JSON content into the property manager. procedure Decode_Part (Into : in out Util.Properties.Manager; Name : in String; Data : in String); function Get_Time (From : in Util.Properties.Manager; Name : in String) return Ada.Calendar.Time is Value : constant String := From.Get (Name); begin return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (Value)); end Get_Time; -- ------------------------------ -- Get the issuer claim from the token (the "iss" claim). -- ------------------------------ function Get_Issuer (From : in Token) return String is begin return From.Claims.Get ("iss"); end Get_Issuer; -- ------------------------------ -- Get the subject claim from the token (the "sub" claim). -- ------------------------------ function Get_Subject (From : in Token) return String is begin return From.Claims.Get ("sub"); end Get_Subject; -- ------------------------------ -- Get the audience claim from the token (the "aud" claim). -- ------------------------------ function Get_Audience (From : in Token) return String is begin return From.Claims.Get ("aud"); end Get_Audience; -- ------------------------------ -- Get the expiration claim from the token (the "exp" claim). -- ------------------------------ function Get_Expiration (From : in Token) return Ada.Calendar.Time is begin return Get_Time (From.Claims, "exp"); end Get_Expiration; -- ------------------------------ -- Get the not before claim from the token (the "nbf" claim). -- ------------------------------ function Get_Not_Before (From : in Token) return Ada.Calendar.Time is begin return Get_Time (From.Claims, "nbf"); end Get_Not_Before; -- ------------------------------ -- Get the issued at claim from the token (the "iat" claim). -- ------------------------------ function Get_Issued_At (From : in Token) return Ada.Calendar.Time is begin return Get_Time (From.Claims, "iat"); end Get_Issued_At; -- ------------------------------ -- Get the authentication time claim from the token (the "auth_time" claim). -- ------------------------------ function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time is begin return Get_Time (From.Claims, "auth_time"); end Get_Authentication_Time; -- ------------------------------ -- Get the JWT ID claim from the token (the "jti" claim). -- ------------------------------ function Get_JWT_ID (From : in Token) return String is begin return From.Claims.Get ("jti"); end Get_JWT_ID; -- ------------------------------ -- Get the authorized clients claim from the token (the "azp" claim). -- ------------------------------ function Get_Authorized_Presenters (From : in Token) return String is begin return From.Claims.Get ("azp"); end Get_Authorized_Presenters; -- ------------------------------ -- Get the claim with the given name from the token. -- ------------------------------ function Get_Claim (From : in Token; Name : in String; Default : in String := "") return String is begin return From.Claims.Get (Name, Default); end Get_Claim; -- ------------------------------ -- Decode the part using base64url and parse the JSON content into the property manager. -- ------------------------------ procedure Decode_Part (Into : in out Util.Properties.Manager; Name : in String; Data : in String) is Decoder : constant Util.Encoders.Encoder := Util.Encoders.Create (Util.Encoders.BASE_64_URL); Content : constant String := Decoder.Decode (Data); begin Log.Debug ("Decoding {0}: {1}", Name, Content); Util.Properties.JSON.Parse_JSON (Into, Content); end Decode_Part; -- ------------------------------ -- Decode a string representing an encoded JWT token according to the JWT specification: -- -- Section 7. Rules for Creating and Validating a JWT -- -- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' . -- The first part represents the header, the second part the claims and the last part -- the signature. The <tt>Decode</tt> operation splits the parts, decodes them, -- parses the JSON content represented by the header and the claims. -- The <tt>Decode</tt> operation does not verify the signature (yet!). -- -- Return the decoded token or raise an exception. -- ------------------------------ function Decode (Content : in String) return Token is Pos1 : constant Natural := Util.Strings.Index (Content, '.'); Pos2 : Natural; Result : Token; begin if Pos1 = 0 then Log.Error ("Invalid JWT token: missing '.' separator. JWT: {0}", Content); raise Invalid_Token with "Missing header separator"; end if; Pos2 := Util.Strings.Index (Content, '.', Pos1 + 1); if Pos2 = 0 then Log.Error ("Invalid JWT token: missing second '.' separator. JWT: {0}", Content); raise Invalid_Token with "Missing signature separator"; end if; Decode_Part (Result.Header, "header", Content (Content'First .. Pos1 - 1)); Decode_Part (Result.Claims, "claims", Content (Pos1 + 1 .. Pos2 - 1)); return Result; exception when Util.Serialize.IO.Parse_Error => raise Invalid_Token with "Invalid JSON content"; end Decode; end Security.OAuth.JWT;
Update Get_Claim to have a default value
Update Get_Claim to have a default value
Ada
apache-2.0
Letractively/ada-security
fefc6bf98cc5716fd57e7f151901910c79cb8e14
awa/src/awa-users-modules.ads
awa/src/awa-users-modules.ads
----------------------------------------------------------------------- -- awa-users-module -- User management module -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with Security.Openid.Servlets; with AWA.Modules; with AWA.Users.Services; with AWA.Users.Filters; with AWA.Users.Servlets; -- == Introduction == -- The <b>Users.Module</b> manages the creation, update, removal and authentication of users -- in an application. The module provides the foundations for user management in -- a web application. -- -- A user can register himself by using a subscription form. In that case, a verification mail -- is sent and the user has to follow the verification link defined in the mail to finish -- the registration process. The user will authenticate using a password. -- -- A user can also use an OpenID account and be automatically registered. -- -- A user can have one or several permissions that allow to protect the application data. -- User permissions are managed by the <b>Permissions.Module</b>. -- -- == Configuration == -- The *users* module uses a set of configuration properties to configure the OpenID -- integration. -- -- @see AWA.Users.Services package AWA.Users.Modules is NAME : constant String := "users"; type User_Module is new AWA.Modules.Module with private; type User_Module_Access is access all User_Module'Class; -- Initialize the user module. overriding procedure Initialize (Plugin : in out User_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the user manager. function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Create a user manager. This operation can be overriden to provide another -- user service implementation. function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Get the user module instance associated with the current application. function Get_User_Module return User_Module_Access; -- Get the user manager instance associated with the current application. function Get_User_Manager return Services.User_Service_Access; private type User_Module is new AWA.Modules.Module with record Manager : Services.User_Service_Access := null; Key_Filter : aliased AWA.Users.Filters.Verify_Filter; Auth_Filter : aliased AWA.Users.Filters.Auth_Filter; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; end record; end AWA.Users.Modules;
----------------------------------------------------------------------- -- awa-users-module -- User management module -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with Security.Openid.Servlets; with AWA.Modules; with AWA.Users.Services; with AWA.Users.Filters; with AWA.Users.Servlets; -- == Introduction == -- The <b>Users.Module</b> manages the creation, update, removal and authentication of users -- in an application. The module provides the foundations for user management in -- a web application. -- -- A user can register himself by using a subscription form. In that case, a verification mail -- is sent and the user has to follow the verification link defined in the mail to finish -- the registration process. The user will authenticate using a password. -- -- A user can also use an OpenID account and be automatically registered. -- -- A user can have one or several permissions that allow to protect the application data. -- User permissions are managed by the <b>Permissions.Module</b>. -- -- == Configuration == -- The *users* module uses a set of configuration properties to configure the OpenID -- integration. -- -- @include awa-users-services.ads -- @include User.hbm.xml package AWA.Users.Modules is NAME : constant String := "users"; type User_Module is new AWA.Modules.Module with private; type User_Module_Access is access all User_Module'Class; -- Initialize the user module. overriding procedure Initialize (Plugin : in out User_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the user manager. function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Create a user manager. This operation can be overriden to provide another -- user service implementation. function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access; -- Get the user module instance associated with the current application. function Get_User_Module return User_Module_Access; -- Get the user manager instance associated with the current application. function Get_User_Manager return Services.User_Service_Access; private type User_Module is new AWA.Modules.Module with record Manager : Services.User_Service_Access := null; Key_Filter : aliased AWA.Users.Filters.Verify_Filter; Auth_Filter : aliased AWA.Users.Filters.Auth_Filter; Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet; Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet; end record; end AWA.Users.Modules;
Integrate the data model and user's bean in the documentation
Integrate the data model and user's bean in the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4ae17b14b4d39be8727580705ccb81b15f66db26
samples/facebook.adb
samples/facebook.adb
----------------------------------------------------------------------- -- facebook -- Get information about a Facebook user using the Facebook API -- 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.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Util.Http.Clients.Web; with Util.Http.Rest; with Mapping; -- This example shows how to invoke a REST service, retrieve and extract a JSON content -- into some Ada record. It uses the Facebook Graph API which does not need any -- authentication (ie, the public Facebook API). procedure Facebook is procedure Print (P : in Mapping.Person); procedure Print (P : in Mapping.Person) is use Ada.Strings.Unbounded; begin Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id)); Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name)); Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name)); Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name)); Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username)); Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender)); Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link)); end Print; procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper); Count : constant Natural := Ada.Command_Line.Argument_Count; -- Mapping for the Person record. Person_Mapping : aliased Mapping.Person_Mapper.Mapper; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: facebook username ..."); Ada.Text_IO.Put_Line ("Example: facebook btaylor"); return; end if; Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID); Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME); Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME); Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME); Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK); Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME); Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER); Util.Http.Clients.Web.Register; for I in 1 .. Count loop declare URI : constant String := Ada.Command_Line.Argument (I); P : aliased Mapping.Person; begin Get_User ("https://graph.facebook.com/" & URI, Person_Mapping'Unchecked_Access, P'Unchecked_Access); Print (P); end; end loop; end Facebook;
----------------------------------------------------------------------- -- facebook -- Get information about a Facebook user using the Facebook API -- 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.Text_IO; with Ada.Command_Line; with Ada.Strings.Unbounded; with Util.Http.Clients.Web; with Util.Http.Rest; with Mapping; -- This example shows how to invoke a REST service, retrieve and extract a JSON content -- into some Ada record. It uses the Facebook Graph API which does not need any -- authentication (ie, the public Facebook API). procedure Facebook is procedure Print (P : in Mapping.Person); procedure Print (P : in Mapping.Person) is use Ada.Strings.Unbounded; begin Ada.Text_IO.Put_Line ("Id : " & Long_Long_Integer'Image (P.Id)); Ada.Text_IO.Put_Line ("Name : " & To_String (P.Name)); Ada.Text_IO.Put_Line ("First name : " & To_String (P.First_Name)); Ada.Text_IO.Put_Line ("Last name : " & To_String (P.Last_Name)); Ada.Text_IO.Put_Line ("Username : " & To_String (P.Username)); Ada.Text_IO.Put_Line ("Gender : " & To_String (P.Gender)); Ada.Text_IO.Put_Line ("Link : " & To_String (P.Link)); end Print; procedure Get_User is new Util.Http.Rest.Rest_Get (Mapping.Person_Mapper); Count : constant Natural := Ada.Command_Line.Argument_Count; -- Mapping for the Person record. Person_Mapping : aliased Mapping.Person_Mapper.Mapper; begin if Count = 0 then Ada.Text_IO.Put_Line ("Usage: facebook username ..."); Ada.Text_IO.Put_Line ("Example: facebook btaylor"); return; end if; Person_Mapping.Add_Mapping ("id", Mapping.FIELD_ID); Person_Mapping.Add_Mapping ("name", Mapping.FIELD_NAME); Person_Mapping.Add_Mapping ("first_name", Mapping.FIELD_FIRST_NAME); Person_Mapping.Add_Mapping ("last_name", Mapping.FIELD_LAST_NAME); Person_Mapping.Add_Mapping ("link", Mapping.FIELD_LINK); Person_Mapping.Add_Mapping ("username", Mapping.FIELD_USER_NAME); Person_Mapping.Add_Mapping ("gender", Mapping.FIELD_GENDER); Util.Http.Clients.Web.Register; for I in 1 .. Count loop declare URI : constant String := Ada.Command_Line.Argument (I); P : aliased Mapping.Person; begin Get_User (URI => "https://graph.facebook.com/" & URI, Mapping => Person_Mapping'Unchecked_Access, Into => P'Unchecked_Access); Print (P); end; end loop; end Facebook;
Fix the call to the Get_User operation
Fix the call to the Get_User operation
Ada
apache-2.0
Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util,flottokarotto/ada-util
0c030d1de447711c6b0636f64d8dfc65ed35babb
src/gen-commands-database.ads
src/gen-commands-database.ads
----------------------------------------------------------------------- -- gen-commands-database -- Database creation from application model -- Copyright (C) 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Database is -- ------------------------------ -- Database Creation Command -- ------------------------------ -- This command creates the database for the application. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out 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 out Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Database;
----------------------------------------------------------------------- -- gen-commands-database -- Database creation from application model -- Copyright (C) 2011, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Database is -- ------------------------------ -- Database Creation Command -- ------------------------------ -- This command creates the database for the application. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out 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 out Command; Name : in String; Generator : in out Gen.Generator.Handler); end Gen.Commands.Database;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
2fda74b6447374adebb93603290f4ec44d953e29
src/security-controllers.ads
src/security-controllers.ads
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; with Security.Permissions; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; with Security.Permissions; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; end Security.Controllers;
Remove the Controller_Factory which is not used
Remove the Controller_Factory which is not used
Ada
apache-2.0
stcarrez/ada-security
2151fa3aa2d816177d4e2dbe041afb1392a30a9c
src/gen-model-beans.adb
src/gen-model-beans.adb
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- 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 Gen.Model.Mappings; package body Gen.Model.Beans is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Bean_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isBean" then return Util.Beans.Objects.To_Object (True); else return Tables.Table_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Bean_Definition) is Iter : Gen.Model.Tables.Column_List.Cursor := O.Members.First; begin while Gen.Model.Tables.Column_List.Has_Element (Iter) loop Gen.Model.Tables.Column_List.Element (Iter).Prepare; Gen.Model.Tables.Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Bean_Definition) is begin O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Create an attribute with the given name and add it to the bean. -- ------------------------------ procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access) is begin Column := new Gen.Model.Tables.Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Bean.Members.Get_Count; Column.Table := Bean'Unchecked_Access; Bean.Members.Append (Column); end Add_Attribute; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access is Bean : constant Bean_Definition_Access := new Bean_Definition; begin Bean.Kind := Mappings.T_BEAN; Bean.Name := Name; declare Pos : constant Natural := Index (Bean.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Bean.Pkg_Name := Unbounded_Slice (Bean.Name, 1, Pos - 1); Bean.Type_Name := Unbounded_Slice (Bean.Name, Pos + 1, Length (Bean.Name)); else Bean.Pkg_Name := To_Unbounded_String ("ADO"); Bean.Type_Name := Bean.Name; end if; end; return Bean; end Create_Bean; end Gen.Model.Beans;
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Gen.Model.Mappings; package body Gen.Model.Beans is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Bean_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "members" or Name = "columns" then return From.Members_Bean; elsif Name = "type" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isBean" then return Util.Beans.Objects.To_Object (True); else return Tables.Table_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Bean_Definition) is Iter : Gen.Model.Tables.Column_List.Cursor := O.Members.First; begin while Gen.Model.Tables.Column_List.Has_Element (Iter) loop Gen.Model.Tables.Column_List.Element (Iter).Prepare; Gen.Model.Tables.Column_List.Next (Iter); end loop; end Prepare; -- ------------------------------ -- Create an attribute with the given name and add it to the bean. -- ------------------------------ procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access) is begin Column := new Gen.Model.Tables.Column_Definition; Column.Name := Name; Column.Sql_Name := Name; Column.Number := Bean.Members.Get_Count; Column.Table := Bean'Unchecked_Access; Bean.Members.Append (Column); end Add_Attribute; -- ------------------------------ -- Create a table with the given name. -- ------------------------------ function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access is Bean : constant Bean_Definition_Access := new Bean_Definition; begin Bean.Kind := Mappings.T_BEAN; Bean.Name := Name; declare Pos : constant Natural := Index (Bean.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Bean.Pkg_Name := Unbounded_Slice (Bean.Name, 1, Pos - 1); Bean.Type_Name := Unbounded_Slice (Bean.Name, Pos + 1, Length (Bean.Name)); else Bean.Pkg_Name := To_Unbounded_String ("ADO"); Bean.Type_Name := Bean.Name; end if; end; return Bean; end Create_Bean; end Gen.Model.Beans;
Remove the Initialize operation
Remove the Initialize operation
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
6fea23aa39dfdd4b834b5c5df712b337fcca6c1a
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- == Step 1: 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, -- associate with us and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Step 2: verify the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- There are basically two steps that an application must implement. -- -- == Step 1: creating the authentication URL == -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenId manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- == Step 2: verify the authentication in the callback URL == -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- OpenID provider -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the OpenID provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
Document the OpenID process
Document the OpenID process
Ada
apache-2.0
Letractively/ada-security
abd1c2b3c683eaf2f7e9e62bbb48c45f1b431d1f
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, 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;
----------------------------------------------------------------------- -- 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); -- 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 Manager; Name : in String) return Util.Beans.Objects.Object is begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object) is begin null; end Set_Value; 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 stubs for the Get_Value and Set_Value operations
Implement stubs for the Get_Value and Set_Value operations
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
de321942df923f89366c4b60d58036d939cd7e06
orka/src/orka/interface/orka-atomics.ads
orka/src/orka/interface/orka-atomics.ads
-- 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. package Orka.Atomics is pragma Pure; protected type Counter (Initial_Value : Natural) is procedure Add (Addition : Natural); procedure Increment; procedure Decrement (Zero : out Boolean); procedure Reset; function Count return Natural; private Value : Natural := Initial_Value; end Counter; end Orka.Atomics;
-- 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. package Orka.Atomics is pragma Pure; protected type Counter (Initial_Value : Natural) is pragma Lock_Free; procedure Add (Addition : Natural); procedure Increment; procedure Decrement (Zero : out Boolean); procedure Reset; function Count return Natural; private Value : Natural := Initial_Value; end Counter; end Orka.Atomics;
Make protected type Counter lock free
orka: Make protected type Counter lock free Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
1f0e6758a80f7d580765d56e57262a535cf90a9e
src/wiki-utils.adb
src/wiki-utils.adb
----------------------------------------------------------------------- -- wiki-utils -- Wiki utility operations -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Render.Text; with Wiki.Render.Html; with Wiki.Writers.Builders; package body Wiki.Utils is -- ------------------------------ -- Render the wiki text according to the wiki syntax in HTML into a string. -- ------------------------------ function To_Html (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Writer : aliased Wiki.Writers.Builders.Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax); return Writer.To_String; end To_Html; -- ------------------------------ -- Render the wiki text according to the wiki syntax in text into a string. -- Wiki formatting and decoration are removed. -- ------------------------------ function To_Text (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax); return Writer.To_String; end To_Text; end Wiki.Utils;
----------------------------------------------------------------------- -- wiki-utils -- Wiki utility operations -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Render.Text; with Wiki.Render.Html; with Wiki.Filters.Html; with Wiki.Writers.Builders; package body Wiki.Utils is -- ------------------------------ -- Render the wiki text according to the wiki syntax in HTML into a string. -- ------------------------------ function To_Html (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Writer : aliased Wiki.Writers.Builders.Html_Writer_Type; Renderer : aliased Wiki.Render.Html.Html_Renderer; Filter : aliased Wiki.Filters.Html.Html_Filter_Type; begin Renderer.Set_Writer (Writer'Unchecked_Access); Filter.Set_Document (Renderer'Unchecked_Access); Wiki.Parsers.Parse (Filter'Unchecked_Access, Text, Syntax); return Writer.To_String; end To_Html; -- ------------------------------ -- Render the wiki text according to the wiki syntax in text into a string. -- Wiki formatting and decoration are removed. -- ------------------------------ function To_Text (Text : in Wide_Wide_String; Syntax : in Wiki.Parsers.Wiki_Syntax_Type) return String is Writer : aliased Wiki.Writers.Builders.Writer_Builder_Type; Renderer : aliased Wiki.Render.Text.Text_Renderer; begin Renderer.Set_Writer (Writer'Unchecked_Access); Wiki.Parsers.Parse (Renderer'Unchecked_Access, Text, Syntax); return Writer.To_String; end To_Text; end Wiki.Utils;
Add the HTML filter in the chain
Add the HTML filter in the chain
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
ec5d7f53470cc327998aca1886ac0a39eccdf0a7
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is Paths : constant String := Registry.Config.Get ("app.modules.dir", "./config"); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration Plugin.Config.Copy (From => Registry.Config, Prefix => Name & ".", Strip => True); Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 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.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration Plugin.Config.Copy (From => Registry.Config, Prefix => Name & ".", Strip => True); Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
Use Applications.P_Module_Dir.P variable instead of hard coded value
Use Applications.P_Module_Dir.P variable instead of hard coded value
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
f318f63a934913baa1c1a120dbf9bd0b9c5dbf0c
awa/src/awa-modules.adb
awa/src/awa-modules.adb
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is Paths : constant String := Registry.Config.Get ("app.modules.dir", "./config"); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration Plugin.Config.Copy (From => Registry.Config, Prefix => Name & ".", Strip => True); Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
----------------------------------------------------------------------- -- awa -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 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.Requests; with ASF.Responses; with ASF.Server; with Ada.IO_Exceptions; with Util.Files; with EL.Contexts.Default; with AWA.Modules.Reader; with AWA.Applications; package body AWA.Modules is -- ------------------------------ -- Get the module name -- ------------------------------ function Get_Name (Plugin : in Module) return String is begin return To_String (Plugin.Name); end Get_Name; -- ------------------------------ -- Get the base URI for this module -- ------------------------------ function Get_URI (Plugin : in Module) return String is begin return To_String (Plugin.URI); end Get_URI; -- ------------------------------ -- Get the application in which this module is registered. -- ------------------------------ function Get_Application (Plugin : in Module) return Application_Access is begin return Plugin.App; end Get_Application; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : Module; Name : String; Default : String := "") return String is begin return Plugin.Config.Get (Name, Default); end Get_Config; -- ------------------------------ -- Get the module configuration property identified by the name. -- If the configuration property does not exist, returns the default value. -- ------------------------------ function Get_Config (Plugin : in Module; Name : in String; Default : in Integer := -1) return Integer is Value : constant String := Plugin.Config.Get (Name, Integer'Image (Default)); begin return Integer'Value (Value); exception when Constraint_Error => return Default; end Get_Config; -- ------------------------------ -- Send the event to the module -- ------------------------------ procedure Send_Event (Plugin : in Module; Content : in AWA.Events.Module_Event'Class) is begin Plugin.App.Send_Event (Content); end Send_Event; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_Module (Plugin : Module; Name : String) return Module_Access is begin if Plugin.Registry = null then return null; end if; return Find_By_Name (Plugin.Registry.all, Name); end Find_Module; -- ------------------------------ -- Register under the given name a function to create the bean instance when -- it is accessed for a first time. The scope defines the scope of the bean. -- bean -- ------------------------------ procedure Register (Plugin : in out Module; Name : in String; Bind : in ASF.Beans.Class_Binding_Access) is begin Plugin.App.Register_Class (Name, Bind); end Register; -- ------------------------------ -- Finalize the module. -- ------------------------------ overriding procedure Finalize (Plugin : in out Module) is begin null; end Finalize; procedure Initialize (Manager : in out Module_Manager; Module : in AWA.Modules.Module'Class) is begin Manager.Module := Module.Self; end Initialize; function Get_Value (Manager : in Module_Manager; Name : in String) return Util.Beans.Objects.Object is pragma Unreferenced (Manager, Name); begin return Util.Beans.Objects.Null_Object; end Get_Value; -- Module manager -- -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module_Manager) return ADO.Sessions.Session is begin return Manager.Module.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module_Manager) return ADO.Sessions.Master_Session is begin return Manager.Module.Get_Master_Session; end Get_Master_Session; -- ------------------------------ -- Send the event to the module. The module identified by <b>To</b> is -- found and the event is posted on its event channel. -- ------------------------------ procedure Send_Event (Manager : in Module_Manager; Content : in AWA.Events.Module_Event'Class) is begin Manager.Module.Send_Event (Content); end Send_Event; procedure Initialize (Plugin : in out Module; App : in Application_Access; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin Plugin.Self := Plugin'Unchecked_Access; Plugin.App := App; end Initialize; -- ------------------------------ -- Initialize the registry -- ------------------------------ procedure Initialize (Registry : in out Module_Registry; Config : in ASF.Applications.Config) is begin Registry.Config := Config; end Initialize; -- ------------------------------ -- Register the module in the registry. -- ------------------------------ procedure Register (Registry : in Module_Registry_Access; App : in Application_Access; Plugin : in Module_Access; Name : in String; URI : in String) is Paths : constant String := Registry.Config.Get (Applications.P_Module_Dir.P); begin Log.Info ("Register module '{0}' under URI '{1}'", Name, URI); if Plugin.Registry /= null then Log.Error ("Module '{0}' is already attached to a registry", Name); raise Program_Error with "Module '" & Name & "' already registered"; end if; Plugin.App := App; Plugin.Registry := Registry; Plugin.Name := To_Unbounded_String (Name); Plugin.URI := To_Unbounded_String (URI); Plugin.Registry.Name_Map.Insert (Name, Plugin); if URI /= "" then Plugin.Registry.URI_Map.Insert (URI, Plugin); end if; -- Load the module configuration file Log.Debug ("Module search path: {0}", Paths); declare Base : constant String := Name & ".properties"; Path : constant String := Util.Files.Find_File_Path (Base, Paths); begin Plugin.Config.Load_Properties (Path => Path, Prefix => Name & ".", Strip => True); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; -- Override the module configuration with the application configuration Plugin.Config.Copy (From => Registry.Config, Prefix => Name & ".", Strip => True); Plugin.Initialize (App, Plugin.Config); -- Read the module XML configuration file if there is one. declare Base : constant String := Plugin.Config.Get ("config", Name & ".xml"); Path : constant String := Util.Files.Find_File_Path (Base, Paths); Ctx : aliased EL.Contexts.Default.Default_Context; begin AWA.Modules.Reader.Read_Configuration (Plugin.all, Path, Ctx'Unchecked_Access); exception when Ada.IO_Exceptions.Name_Error => Log.Warn ("Module configuration file '{0}' does not exist", Path); end; exception when Constraint_Error => Log.Error ("Another module is already registered " & "under name '{0}' or URI '{1}'", Name, URI); raise; end Register; -- ------------------------------ -- Find the module with the given name -- ------------------------------ function Find_By_Name (Registry : Module_Registry; Name : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.Name_Map, Name); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_Name; -- ------------------------------ -- Find the module mapped to a given URI -- ------------------------------ function Find_By_URI (Registry : Module_Registry; URI : String) return Module_Access is Pos : constant Module_Maps.Cursor := Module_Maps.Find (Registry.URI_Map, URI); begin if Module_Maps.Has_Element (Pos) then return Module_Maps.Element (Pos); end if; return null; end Find_By_URI; -- ------------------------------ -- Get the database connection for reading -- ------------------------------ function Get_Session (Manager : Module) return ADO.Sessions.Session is begin return Manager.App.Get_Session; end Get_Session; -- ------------------------------ -- Get the database connection for writing -- ------------------------------ function Get_Master_Session (Manager : Module) return ADO.Sessions.Master_Session is begin return Manager.App.Get_Master_Session; end Get_Master_Session; -- Get per request manager => look in Request -- Get per session manager => look in Request.Get_Session -- Get per application manager => look in Application -- Get per pool manager => look in pool attached to Application function Get_Manager return Manager_Type_Access is procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class); Value : Util.Beans.Objects.Object; procedure Process (Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is pragma Unreferenced (Response); begin Value := Request.Get_Attribute (Name); if Util.Beans.Objects.Is_Null (Value) then declare M : constant Manager_Type_Access := new Manager_Type; begin Value := Util.Beans.Objects.To_Object (M.all'Access); Request.Set_Attribute (Name, Value); end; end if; end Process; begin ASF.Server.Update_Context (Process'Access); if Util.Beans.Objects.Is_Null (Value) then return null; end if; declare B : constant access Util.Beans.Basic.Readonly_Bean'Class := Util.Beans.Objects.To_Bean (Value); begin if not (B.all in Manager_Type'Class) then return null; end if; return Manager_Type'Class (B.all)'Unchecked_Access; end; end Get_Manager; end AWA.Modules;
Use Applications.P_Module_Dir.P variable instead of hard coded value
Use Applications.P_Module_Dir.P variable instead of hard coded value
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
91a66228861c586e94912230616ed17c29a4dfa9
awa/plugins/awa-settings/src/awa-settings.adb
awa/plugins/awa-settings/src/awa-settings.adb
----------------------------------------------------------------------- -- awa-settings -- Settings module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with AWA.Settings.Modules; package body AWA.Settings is -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in String) return String is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; Value : Ada.Strings.Unbounded.Unbounded_String; begin Mgr.Get (Name, Default, Value); return Ada.Strings.Unbounded.To_String (Value); end Get_User_Setting; -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in Integer) return Integer is begin return Default; end Get_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in String) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Value); end Set_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in Integer) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Util.Strings.Image (Value)); end Set_User_Setting; end AWA.Settings;
----------------------------------------------------------------------- -- awa-settings -- Settings module -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings; with AWA.Settings.Modules; package body AWA.Settings is -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in String) return String is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; Value : Ada.Strings.Unbounded.Unbounded_String; begin Mgr.Get (Name, Default, Value); return Ada.Strings.Unbounded.To_String (Value); end Get_User_Setting; -- ------------------------------ -- Get the user setting identified by the given name. -- If the user does not have such setting, return the default value. -- ------------------------------ function Get_User_Setting (Name : in String; Default : in Integer) return Integer is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; Value : Ada.Strings.Unbounded.Unbounded_String; begin Mgr.Get (Name, Integer'Image (Default), Value); return Integer'Value (Ada.Strings.Unbounded.To_String (Value)); end Get_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in String) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Value); end Set_User_Setting; -- ------------------------------ -- Set the user setting identified by the given name. If the user -- does not have such setting, it is created and set to the given value. -- Otherwise, the user setting is updated to hold the new value. -- ------------------------------ procedure Set_User_Setting (Name : in String; Value : in Integer) is Mgr : constant AWA.Settings.Modules.Setting_Manager_Access := AWA.Settings.Modules.Current; begin Mgr.Set (Name, Util.Strings.Image (Value)); end Set_User_Setting; end AWA.Settings;
Implement Get_User_Setting for integer
Implement Get_User_Setting for integer
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa
09597de638aa7dc54966c23498509ea6f021fb28
awa/src/awa-permissions.ads
awa/src/awa-permissions.ads
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 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 Security.Permissions; with Security.Policies; with Util.Serialize.IO.XML; with ADO; with ADO.Objects; -- == Introduction == -- The *AWA.Permissions* framework defines and controls the permissions used by an application -- to verify and grant access to the data and application service. The framework provides a -- set of services and API that helps an application in enforcing its specific permissions. -- Permissions are verified by a permission controller which uses the service context to -- have information about the user and other context. The framework allows to use different -- kinds of permission controllers. The `Entity_Controller` is the default permission -- controller which uses the database and an XML configuration to verify a permission. -- -- === Declaration === -- To be used in the application, the first step is to declare the permission. -- This is a static definition of the permission that will be used to ask to verify the -- permission. The permission is given a unique name that will be used in configuration files: -- -- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); -- -- === Checking for a permission === -- A permission can be checked in Ada as well as in the presentation pages. -- This is done by using the `Check` procedure and the permission definition. This operation -- acts as a barrier: it does not return anything but returns normally if the permission is -- granted. If the permission is denied, it raises the `NO_PERMISSION` exception. -- -- Several `Check` operation exists. Some require no argument and some others need a context -- such as some entity identifier to perform the check. -- -- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, -- Entity => Blog_Id); -- -- === Configuring a permission === -- The *AWA.Permissions* framework supports a simple permission model -- The application configuration file must provide some information to help in checking the -- permission. The permission name is referenced by the `name` XML entity. The `entity-type` -- refers to the database entity (ie, the table) that the permission concerns. -- The `sql` XML entity represents the SQL statement that must be used to verify the permission. -- -- <entity-permission> -- <name>blog-create-post</name> -- <entity-type>blog</entity-type> -- <description>Permission to create a new post.</description> -- <sql> -- SELECT acl.id FROM acl -- WHERE acl.entity_type = :entity_type -- AND acl.user_id = :user_id -- AND acl.entity_id = :entity_id -- </sql> -- </entity-permission> -- -- === Adding a permission === -- Adding a permission means to create an `ACL` database record that links a given database -- entity to the user. This is done easily with the `Add_Permission` procedure: -- -- AWA.Permissions.Services.Add_Permission (Session => DB, -- User => User, -- Entity => Blog); -- -- == Data Model == -- @include Permission.hbm.xml -- -- == Queries == -- @include permissions.xml -- package AWA.Permissions is NAME : constant String := "Entity-Policy"; -- Exception raised by the <b>Check</b> procedure if the user does not have -- the permission. NO_PERMISSION : exception; -- Maximum number of entity types that can be defined in the XML entity-permission. -- Most permission need only one entity type. Keep that number small. MAX_ENTITY_TYPES : constant Positive := 5; type Entity_Type_Array is array (1 .. MAX_ENTITY_TYPES) of ADO.Entity_Type; type Permission_Type is (READ, WRITE); type Entity_Permission is new Security.Permissions.Permission with private; -- Verify that the permission represented by <b>Permission</b> is granted. -- procedure Check (Permission : in Security.Permissions.Permission_Index); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier); -- 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.Objects.Object_Ref'Class); private type Entity_Permission is new Security.Permissions.Permission with record Entity : ADO.Identifier; end record; type Entity_Policy is new Security.Policies.Policy with null record; type Entity_Policy_Access is access all Entity_Policy'Class; -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 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 Security.Permissions; with Security.Policies; with Util.Serialize.IO.XML; with ADO; with ADO.Objects; -- == Introduction == -- The *AWA.Permissions* framework defines and controls the permissions used by an application -- to verify and grant access to the data and application service. The framework provides a -- set of services and API that helps an application in enforcing its specific permissions. -- Permissions are verified by a permission controller which uses the service context to -- have information about the user and other context. The framework allows to use different -- kinds of permission controllers. The `Entity_Controller` is the default permission -- controller which uses the database and an XML configuration to verify a permission. -- -- === Declaration === -- To be used in the application, the first step is to declare the permission. -- This is a static definition of the permission that will be used to ask to verify the -- permission. The permission is given a unique name that will be used in configuration files: -- -- with Security.Permissions; -- ... -- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); -- -- === Checking for a permission === -- A permission can be checked in Ada as well as in the presentation pages. -- This is done by using the `Check` procedure and the permission definition. This operation -- acts as a barrier: it does not return anything but returns normally if the permission is -- granted. If the permission is denied, it raises the `NO_PERMISSION` exception. -- -- Several `Check` operation exists. Some require no argument and some others need a context -- such as some entity identifier to perform the check. -- -- with AWA.Permissions; -- ... -- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, -- Entity => Blog_Id); -- -- === Configuring a permission === -- The *AWA.Permissions* framework supports a simple permission model -- The application configuration file must provide some information to help in checking the -- permission. The permission name is referenced by the `name` XML entity. The `entity-type` -- refers to the database entity (ie, the table) that the permission concerns. -- The `sql` XML entity represents the SQL statement that must be used to verify the permission. -- -- <entity-permission> -- <name>blog-create-post</name> -- <entity-type>blog</entity-type> -- <description>Permission to create a new post.</description> -- <sql> -- SELECT acl.id FROM acl -- WHERE acl.entity_type = :entity_type -- AND acl.user_id = :user_id -- AND acl.entity_id = :entity_id -- </sql> -- </entity-permission> -- -- === Adding a permission === -- Adding a permission means to create an `ACL` database record that links a given database -- entity to the user. This is done easily with the `Add_Permission` procedure: -- -- with AWA.Permissions.Services; -- ... -- AWA.Permissions.Services.Add_Permission (Session => DB, -- User => User, -- Entity => Blog); -- -- == Data Model == -- [images/awa_permissions_model.png] -- -- == Queries == -- @include permissions.xml -- package AWA.Permissions is NAME : constant String := "Entity-Policy"; -- Exception raised by the <b>Check</b> procedure if the user does not have -- the permission. NO_PERMISSION : exception; -- Maximum number of entity types that can be defined in the XML entity-permission. -- Most permission need only one entity type. Keep that number small. MAX_ENTITY_TYPES : constant Positive := 5; type Entity_Type_Array is array (1 .. MAX_ENTITY_TYPES) of ADO.Entity_Type; type Permission_Type is (READ, WRITE); type Entity_Permission is new Security.Permissions.Permission with private; -- Verify that the permission represented by <b>Permission</b> is granted. -- procedure Check (Permission : in Security.Permissions.Permission_Index); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier); -- 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.Objects.Object_Ref'Class); private type Entity_Permission is new Security.Permissions.Permission with record Entity : ADO.Identifier; end record; type Entity_Policy is new Security.Policies.Policy with null record; type Entity_Policy_Access is access all Entity_Policy'Class; -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser); end AWA.Permissions;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c23b17dba612530f511768306e5cad2dc9b9f115
src/wiki-render-html.adb
src/wiki-render-html.adb
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Render the node instance from the document. -- ------------------------------ overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Render_Header (Header => Node.Header, Level => Node.Level); when Wiki.Nodes.N_LINE_BREAK => Engine.Output.Start_Element ("br"); Engine.Output.End_Element ("br"); when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Add_Blockquote (0); Engine.Output.Start_Element ("hr"); Engine.Output.End_Element ("hr"); when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; when Wiki.Nodes.N_INDENT => -- Engine.Indent_Level := Node.Level; null; when Wiki.Nodes.N_TEXT => Engine.Add_Text (Text => Node.Text, Format => Node.Format); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); when Wiki.Nodes.N_LINK => Engine.Render_Link (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_BLOCKQUOTE => Engine.Add_Blockquote (Node.Level); when Wiki.Nodes.N_TAG_START => Engine.Render_Tag (Doc, Node); end case; end Render; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start); Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes); begin if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := True; Engine.Need_Paragraph := False; end if; Engine.Output.Start_Element (Name.all); while Wiki.Attributes.Has_Element (Iter) loop Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := False; Engine.Need_Paragraph := True; end if; Engine.Output.End_Element (Name.all); end Render_Tag; -- ------------------------------ -- Render a section header in the document. -- ------------------------------ procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive) is begin Engine.Close_Paragraph; Engine.Add_Blockquote (0); case Level is when 1 => Engine.Output.Write_Wide_Element ("h1", Header); when 2 => Engine.Output.Write_Wide_Element ("h2", Header); when 3 => Engine.Output.Write_Wide_Element ("h3", Header); when 4 => Engine.Output.Write_Wide_Element ("h4", Header); when 5 => Engine.Output.Write_Wide_Element ("h5", Header); when 6 => Engine.Output.Write_Wide_Element ("h6", Header); when others => Engine.Output.Write_Wide_Element ("h3", Header); end case; end Render_Header; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Output.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Output.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Output.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Output.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Output.Start_Element ("ol"); else Document.Output.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Output.End_Element ("p"); end if; if Document.Has_Item then Document.Output.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Output.End_Element ("ol"); else Document.Output.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Output.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Output.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Exists : Boolean; Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "hreflang" or Name = "title" or Name = "rel" or Name = "target" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); Engine.Links.Make_Page_Link (Link, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "alt" or Name = "longdesc" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("img"); Engine.Links.Make_Image_Link (Link, URI, Width, Height); Engine.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Engine.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Engine.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.End_Element ("img"); end Render_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Open_Paragraph; Document.Output.Start_Element ("q"); if Length (Language) > 0 then Document.Output.Write_Wide_Attribute ("lang", Language); end if; if Length (Link) > 0 then Document.Output.Write_Wide_Attribute ("cite", Link); end if; -- Document.Output.Write_Wide_Text (Quote); Document.Output.End_Element ("q"); end Add_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (Documents.BOLD => HTML_BOLD'Access, Documents.ITALIC => HTML_ITALIC'Access, Documents.CODE => HTML_CODE'Access, Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access, Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access, Documents.STRIKEOUT => HTML_STRIKEOUT'Access, Documents.PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Documents.Format_Map) is begin Engine.Open_Paragraph; for I in Format'Range loop if Format (I) then Engine.Output.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Engine.Output.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Engine.Output.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Output.Write (To_Wide_Wide_String (Text)); else Document.Output.Start_Element ("pre"); -- Document.Output.Write_Wide_Text (Text); Document.Output.End_Element ("pre"); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Util.Strings; package body Wiki.Render.Html is package ACC renames Ada.Characters.Conversions; -- ------------------------------ -- Set the output stream. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the link renderer. -- ------------------------------ procedure Set_Link_Renderer (Document : in out Html_Renderer; Links : in Link_Renderer_Access) is begin Document.Links := Links; end Set_Link_Renderer; -- ------------------------------ -- Render the node instance from the document. -- ------------------------------ overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Render_Header (Header => Node.Header, Level => Node.Level); when Wiki.Nodes.N_LINE_BREAK => Engine.Output.Start_Element ("br"); Engine.Output.End_Element ("br"); when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Add_Blockquote (0); Engine.Output.Start_Element ("hr"); Engine.Output.End_Element ("hr"); when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; when Wiki.Nodes.N_INDENT => -- Engine.Indent_Level := Node.Level; null; when Wiki.Nodes.N_TEXT => Engine.Add_Text (Text => Node.Text, Format => Node.Format); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); when Wiki.Nodes.N_LINK => Engine.Render_Link (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Doc, Node.Title, Node.Link_Attr); when Wiki.Nodes.N_BLOCKQUOTE => Engine.Add_Blockquote (Node.Level); when Wiki.Nodes.N_TAG_START => Engine.Render_Tag (Doc, Node); end case; end Render; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Html_Tag_Type; Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start); Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes); begin if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := True; Engine.Need_Paragraph := False; end if; Engine.Output.Start_Element (Name.all); while Wiki.Attributes.Has_Element (Iter) loop Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter), Content => Wiki.Attributes.Get_Wide_Value (Iter)); Wiki.Attributes.Next (Iter); end loop; Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.Nodes.P_TAG then Engine.Has_Paragraph := False; Engine.Need_Paragraph := True; end if; Engine.Output.End_Element (Name.all); end Render_Tag; -- ------------------------------ -- Render a section header in the document. -- ------------------------------ procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive) is begin Engine.Close_Paragraph; Engine.Add_Blockquote (0); case Level is when 1 => Engine.Output.Write_Wide_Element ("h1", Header); when 2 => Engine.Output.Write_Wide_Element ("h2", Header); when 3 => Engine.Output.Write_Wide_Element ("h3", Header); when 4 => Engine.Output.Write_Wide_Element ("h4", Header); when 5 => Engine.Output.Write_Wide_Element ("h5", Header); when 6 => Engine.Output.Write_Wide_Element ("h6", Header); when others => Engine.Output.Write_Wide_Element ("h3", Header); end case; end Render_Header; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Html_Renderer; Level : in Natural) is begin if Document.Quote_Level /= Level then Document.Close_Paragraph; Document.Need_Paragraph := True; end if; while Document.Quote_Level < Level loop Document.Output.Start_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level + 1; end loop; while Document.Quote_Level > Level loop Document.Output.End_Element ("blockquote"); Document.Quote_Level := Document.Quote_Level - 1; end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Html_Renderer; Level : in Positive; Ordered : in Boolean) is begin if Document.Has_Paragraph then Document.Output.End_Element ("p"); Document.Has_Paragraph := False; end if; if Document.Has_Item then Document.Output.End_Element ("li"); Document.Has_Item := False; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; while Document.Current_Level < Level loop if Ordered then Document.Output.Start_Element ("ol"); else Document.Output.Start_Element ("ul"); end if; Document.Current_Level := Document.Current_Level + 1; Document.List_Styles (Document.Current_Level) := Ordered; end loop; end Add_List_Item; procedure Close_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Has_Paragraph then Document.Output.End_Element ("p"); end if; if Document.Has_Item then Document.Output.End_Element ("li"); end if; while Document.Current_Level > 0 loop if Document.List_Styles (Document.Current_Level) then Document.Output.End_Element ("ol"); else Document.Output.End_Element ("ul"); end if; Document.Current_Level := Document.Current_Level - 1; end loop; Document.Has_Paragraph := False; Document.Has_Item := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Html_Renderer) is begin if Document.Html_Level > 0 then return; end if; if Document.Need_Paragraph then Document.Output.Start_Element ("p"); Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; if Document.Current_Level > 0 and not Document.Has_Item then Document.Output.Start_Element ("li"); Document.Has_Item := True; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Exists : Boolean; Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "hreflang" or Name = "title" or Name = "rel" or Name = "target" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("a"); Engine.Links.Make_Page_Link (Link, URI, Exists); Engine.Output.Write_Wide_Attribute ("href", URI); Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.Write_Wide_Text (Title); Engine.Output.End_Element ("a"); end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Nodes.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List_Type) is Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Attribute (Attr, "href"); URI : Unbounded_Wide_Wide_String; Width : Natural; Height : Natural; procedure Render_Attribute (Name : in String; Value : in Wide_Wide_String) is begin if Name = "alt" or Name = "longdesc" or Name = "style" or Name = "class" then Engine.Output.Write_Wide_Attribute (Name, Value); end if; end Render_Attribute; begin Engine.Open_Paragraph; Engine.Output.Start_Element ("img"); Engine.Links.Make_Image_Link (Link, URI, Width, Height); Engine.Output.Write_Wide_Attribute ("src", URI); if Width > 0 then Engine.Output.Write_Attribute ("width", Natural'Image (Width)); end if; if Height > 0 then Engine.Output.Write_Attribute ("height", Natural'Image (Height)); end if; Wiki.Attributes.Iterate (Attr, Render_Attribute'Access); Engine.Output.End_Element ("img"); end Render_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Document : in out Html_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is begin Document.Open_Paragraph; Document.Output.Start_Element ("q"); if Length (Language) > 0 then Document.Output.Write_Wide_Attribute ("lang", Language); end if; if Length (Link) > 0 then Document.Output.Write_Wide_Attribute ("cite", Link); end if; -- Document.Output.Write_Wide_Text (Quote); Document.Output.End_Element ("q"); end Add_Quote; HTML_BOLD : aliased constant String := "b"; HTML_ITALIC : aliased constant String := "i"; HTML_CODE : aliased constant String := "tt"; HTML_SUPERSCRIPT : aliased constant String := "sup"; HTML_SUBSCRIPT : aliased constant String := "sub"; HTML_STRIKEOUT : aliased constant String := "del"; -- HTML_UNDERLINE : aliased constant String := "ins"; HTML_PREFORMAT : aliased constant String := "pre"; type String_Array_Access is array (Format_Type) of Util.Strings.Name_Access; HTML_ELEMENT : constant String_Array_Access := (BOLD => HTML_BOLD'Access, ITALIC => HTML_ITALIC'Access, CODE => HTML_CODE'Access, SUPERSCRIPT => HTML_SUPERSCRIPT'Access, SUBSCRIPT => HTML_SUBSCRIPT'Access, STRIKEOUT => HTML_STRIKEOUT'Access, PREFORMAT => HTML_PREFORMAT'Access); -- ------------------------------ -- Add a text block with the given format. -- ------------------------------ procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is begin Engine.Open_Paragraph; for I in Format'Range loop if Format (I) then Engine.Output.Start_Element (HTML_ELEMENT (I).all); end if; end loop; Engine.Output.Write_Wide_Text (Text); for I in reverse Format'Range loop if Format (I) then Engine.Output.End_Element (HTML_ELEMENT (I).all); end if; end loop; end Add_Text; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Html_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is begin Document.Close_Paragraph; if Format = "html" then Document.Output.Write (To_Wide_Wide_String (Text)); else Document.Output.Start_Element ("pre"); -- Document.Output.Write_Wide_Text (Text); Document.Output.End_Element ("pre"); end if; end Add_Preformatted; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Html_Renderer) is begin Document.Close_Paragraph; Document.Add_Blockquote (0); end Finish; end Wiki.Render.Html;
Use Wiki.Format_Map type
Use Wiki.Format_Map type
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
11d505cb431b25350ca66c2c85439d5c0190cb17
src/wiki-render-html.ads
src/wiki-render-html.ads
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Engine : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Html_Renderer; Level : in Natural); -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Render_List_Item (Engine : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Engine : in out Html_Renderer); private procedure Close_Paragraph (Engine : in out Html_Renderer); procedure Open_Paragraph (Engine : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); end Wiki.Render.Html;
----------------------------------------------------------------------- -- wiki-render-html -- Wiki HTML renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Attributes; with Wiki.Streams.Html; with Wiki.Strings; -- == HTML Renderer == -- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content. -- The formatting rules are ignored except for the paragraphs and sections. package Wiki.Render.Html is -- ------------------------------ -- Wiki to HTML renderer -- ------------------------------ type Html_Renderer is new Renderer with private; -- Set the output stream. procedure Set_Output_Stream (Engine : in out Html_Renderer; Stream : in Wiki.Streams.Html.Html_Output_Stream_Access); -- Set the link renderer. procedure Set_Link_Renderer (Engine : in out Html_Renderer; Links : in Link_Renderer_Access); -- Render the node instance from the document. overriding procedure Render (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. procedure Add_Blockquote (Engine : in out Html_Renderer; Level : in Natural); -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. procedure Render_List_Item (Engine : in out Html_Renderer; Level : in Positive; Ordered : in Boolean); -- Add a text block with the given format. procedure Add_Text (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Html_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString); -- Finish the document after complete wiki text has been parsed. overriding procedure Finish (Engine : in out Html_Renderer); private procedure Close_Paragraph (Engine : in out Html_Renderer); procedure Open_Paragraph (Engine : in out Html_Renderer); type List_Style_Array is array (1 .. 32) of Boolean; Default_Links : aliased Default_Link_Renderer; type Html_Renderer is new Renderer with record Output : Wiki.Streams.Html.Html_Output_Stream_Access := null; Format : Wiki.Format_Map := (others => False); Links : Link_Renderer_Access := Default_Links'Access; Has_Paragraph : Boolean := False; Need_Paragraph : Boolean := False; Has_Item : Boolean := False; Current_Level : Natural := 0; List_Styles : List_Style_Array := (others => False); Quote_Level : Natural := 0; Html_Level : Natural := 0; end record; procedure Render_Tag (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type); -- Render a section header in the document. procedure Render_Header (Engine : in out Html_Renderer; Header : in Wiki.Strings.WString; Level : in Positive); -- Render the table of content. procedure Render_Toc (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Level : in Natural); -- Render a link. procedure Render_Link (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render an image. procedure Render_Image (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Html_Renderer; Doc : in Wiki.Documents.Document; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List); end Wiki.Render.Html;
Declare the Render_Toc procedure
Declare the Render_Toc procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5e3899b3ea312d78268c6461947048454479321e
src/wiki-filters-toc.adb
src/wiki-filters-toc.adb
----------------------------------------------------------------------- -- wiki-filters-toc -- Filter for the creation of Table Of Contents -- Copyright (C) 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Fixed; with Wiki.Nodes; package body Wiki.Filters.TOC is -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ overriding procedure Add_Text (Filter : in out TOC_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is use Ada.Strings.Wide_Wide_Fixed; First : Natural := Text'First; Pos : Natural; begin while First <= Text'Last loop Pos := Index (Text (First .. Text'Last), "__TOC__"); if Pos > 0 then Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format); Filter.Add_Node (Document, Wiki.Nodes.N_TOC_DISPLAY); First := Pos + 7; else Pos := Index (Text (First .. Text'Last), "__NOTOC__"); if Pos > 0 then Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format); Document.Hide_TOC; First := Pos + 9; else Filter_Type (Filter).Add_Text (Document, Text (First .. Text'Last), Format); exit; end if; end if; end loop; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ overriding procedure Add_Header (Filter : in out TOC_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is T : Wiki.Nodes.Node_List_Ref; begin Document.Get_TOC (T); Wiki.Nodes.Append (T, new Wiki.Nodes.Node_Type '(Kind => Wiki.Nodes.N_TOC_ENTRY, Len => Header'Length, Header => Header, Level => Level)); Filter_Type (Filter).Add_Header (Document, Header, Level); end Add_Header; end Wiki.Filters.TOC;
----------------------------------------------------------------------- -- wiki-filters-toc -- Filter for the creation of Table Of Contents -- Copyright (C) 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Fixed; with Wiki.Nodes.Lists; package body Wiki.Filters.TOC is -- ------------------------------ -- Add a text content with the given format to the document. -- ------------------------------ overriding procedure Add_Text (Filter : in out TOC_Filter; Document : in out Wiki.Documents.Document; Text : in Wiki.Strings.WString; Format : in Wiki.Format_Map) is use Ada.Strings.Wide_Wide_Fixed; First : Natural := Text'First; Pos : Natural; begin while First <= Text'Last loop Pos := Index (Text (First .. Text'Last), "__TOC__"); if Pos > 0 then Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format); Filter.Add_Node (Document, Wiki.Nodes.N_TOC_DISPLAY); First := Pos + 7; else Pos := Index (Text (First .. Text'Last), "__NOTOC__"); if Pos > 0 then Filter_Type (Filter).Add_Text (Document, Text (First .. Pos - 1), Format); Document.Hide_TOC; First := Pos + 9; else Filter_Type (Filter).Add_Text (Document, Text (First .. Text'Last), Format); exit; end if; end if; end loop; end Add_Text; -- ------------------------------ -- Add a section header with the given level in the document. -- ------------------------------ overriding procedure Add_Header (Filter : in out TOC_Filter; Document : in out Wiki.Documents.Document; Header : in Wiki.Strings.WString; Level : in Natural) is T : Wiki.Nodes.Lists.Node_List_Ref; begin Document.Get_TOC (T); Wiki.Nodes.Lists.Append (T, new Wiki.Nodes.Node_Type '(Kind => Wiki.Nodes.N_TOC_ENTRY, Len => Header'Length, Header => Header, Level => Level)); Filter_Type (Filter).Add_Header (Document, Header, Level); end Add_Header; end Wiki.Filters.TOC;
Update to use the new Node_List_Ref reference
Update to use the new Node_List_Ref reference
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
03027ca33441d2b97c95602646e91c043e33399e
tools/druss-gateways.ads
tools/druss-gateways.ads
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Util.Properties; with Util.Refs; with Bbox.API; package Druss.Gateways is type State_Type is (IDLE, READY, BUSY); protected type Gateway_State is function Get_State return State_Type; private State : State_Type := IDLE; end Gateway_State; type Gateway_Type is limited new Util.Refs.Ref_Entity with record -- Gateway IP address. Ip : Ada.Strings.Unbounded.Unbounded_String; -- API password. Passwd : Ada.Strings.Unbounded.Unbounded_String; -- Directory that contains the images. Images : Ada.Strings.Unbounded.Unbounded_String; -- The gateway state. State : Gateway_State; -- Current WAN information (from api/v1/wan). Wan : Util.Properties.Manager; -- Current LAN information (from api/v1/lan). Lan : Util.Properties.Manager; -- Wireless information (From api/v1/wireless). Wifi : Util.Properties.Manager; -- Current Device information (from api/v1/device). Device : Util.Properties.Manager; -- The Bbox API client. Client : Bbox.API.Client_Type; end record; type Gateway_Type_Access is access all Gateway_Type; -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in out Gateway_Type); package Gateway_Refs is new Util.Refs.References (Element_Type => Gateway_Type, Element_Access => Gateway_Type_Access); subtype Gateway_Ref is Gateway_Refs.Ref; function "=" (Left, Right : in Gateway_Ref) return Boolean; package Gateway_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Gateway_Ref, "=" => "="); subtype Gateway_Vector is Gateway_Vectors.Vector; subtype Gateway_Cursor is Gateway_Vectors.Cursor; -- Initalize the list of gateways from the property list. procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector); -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in Gateway_Ref) with pre => not Gateway.Is_Null; -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. procedure Iterate (List : in Gateway_Vector; Process : not null access procedure (G : in out Gateway_Type)); end Druss.Gateways;
----------------------------------------------------------------------- -- druss-gateways -- Gateway management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Ada.Strings.Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Properties; with Util.Refs; with Bbox.API; package Druss.Gateways is Not_Found : exception; type State_Type is (IDLE, READY, BUSY); protected type Gateway_State is function Get_State return State_Type; private State : State_Type := IDLE; end Gateway_State; type Gateway_Type is limited new Util.Refs.Ref_Entity with record -- Gateway IP address. Ip : Ada.Strings.Unbounded.Unbounded_String; -- API password. Passwd : Ada.Strings.Unbounded.Unbounded_String; -- The Bbox serial number. Serial : Ada.Strings.Unbounded.Unbounded_String; -- Directory that contains the images. Images : Ada.Strings.Unbounded.Unbounded_String; -- The gateway state. State : Gateway_State; -- Current WAN information (from api/v1/wan). Wan : Util.Properties.Manager; -- Current LAN information (from api/v1/lan). Lan : Util.Properties.Manager; -- Wireless information (From api/v1/wireless). Wifi : Util.Properties.Manager; -- Current Device information (from api/v1/device). Device : Util.Properties.Manager; -- The Bbox API client. Client : Bbox.API.Client_Type; end record; type Gateway_Type_Access is access all Gateway_Type; -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in out Gateway_Type); package Gateway_Refs is new Util.Refs.References (Element_Type => Gateway_Type, Element_Access => Gateway_Type_Access); subtype Gateway_Ref is Gateway_Refs.Ref; function "=" (Left, Right : in Gateway_Ref) return Boolean; package Gateway_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Gateway_Ref, "=" => "="); subtype Gateway_Vector is Gateway_Vectors.Vector; subtype Gateway_Cursor is Gateway_Vectors.Cursor; package Gateway_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Gateway_Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); -- Initalize the list of gateways from the property list. procedure Initialize (Config : in Util.Properties.Manager; List : in out Gateway_Vector); -- Save the list of gateways. procedure Save_Gateways (Config : in out Util.Properties.Manager; List : in Druss.Gateways.Gateway_Vector); -- Refresh the information by using the Bbox API. procedure Refresh (Gateway : in Gateway_Ref) with pre => not Gateway.Is_Null; -- Iterate over the list of gateways and execute the <tt>Process</tt> procedure. procedure Iterate (List : in Gateway_Vector; Process : not null access procedure (G : in out Gateway_Type)); -- Find the gateway with the given IP address. function Find_IP (List : in Gateway_Vector; IP : in String) return Gateway_Ref; end Druss.Gateways;
Declare Save_Gateways and Find_IP operation
Declare Save_Gateways and Find_IP operation
Ada
apache-2.0
stcarrez/bbox-ada-api
0aa93d536f012e5f92d3ab86753e7759d3f00e63
regtests/util-files-tests.ads
regtests/util-files-tests.ads
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Files.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Read_File (T : in out Test); procedure Test_Read_File_Missing (T : in out Test); procedure Test_Read_File_Truncate (T : in out Test); procedure Test_Write_File (T : in out Test); procedure Test_Find_File_Path (T : in out Test); procedure Test_Iterate_Path (T : in out Test); procedure Test_Compose_Path (T : in out Test); -- Test the Get_Relative_Path operation. procedure Test_Get_Relative_Path (T : in out Test); -- Test the Delete_Tree operation. procedure Test_Delete_Tree (T : in out Test); end Util.Files.Tests;
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Files.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Read_File (T : in out Test); procedure Test_Read_File_Missing (T : in out Test); procedure Test_Read_File_Truncate (T : in out Test); procedure Test_Write_File (T : in out Test); procedure Test_Find_File_Path (T : in out Test); procedure Test_Iterate_Path (T : in out Test); procedure Test_Compose_Path (T : in out Test); -- Test the Get_Relative_Path operation. procedure Test_Get_Relative_Path (T : in out Test); -- Test the Delete_Tree operation. procedure Test_Delete_Tree (T : in out Test); -- Test the Realpath function. procedure Test_Realpath (T : in out Test); end Util.Files.Tests;
Declare the Test_Realpath procedure
Declare the Test_Realpath procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
8221784a09504bacc56571e675eac216134933be
mat/src/mat-readers-files.adb
mat/src/mat-readers-files.adb
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); BUFFER_SIZE : constant Natural := 100 * 1024; MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048; -- Open the file. procedure Open (Reader : in out File_Reader_Type; Path : in String) is begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.File'Unchecked_Access, Output => null); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; procedure Read_All (Reader : in out File_Reader_Type) is use Ada.Streams; use type MAT.Types.Uint8; Data : aliased Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE); Buffer : aliased Buffer_Type; Msg : Message; Last : Ada.Streams.Stream_Element_Offset; Format : MAT.Types.Uint8; begin Msg.Buffer := Buffer'Unchecked_Access; Msg.Buffer.Start := Data (0)'Address; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (MAX_MSG_SIZE)'Address; Msg.Buffer.Size := 3; Reader.Stream.Read (Data (0 .. 2), Last); Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer); if Format = 0 then Msg.Buffer.Endian := LITTLE_ENDIAN; Log.Debug ("Data stream is little endian"); else Msg.Buffer.Endian := BIG_ENDIAN; Log.Debug ("Data stream is big endian"); end if; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (Last)'Address; Msg.Buffer.Size := Msg.Size; Reader.Read_Headers (Msg); while not Reader.Stream.Is_Eof loop Reader.Stream.Read (Data (0 .. 1), Last); exit when Last /= 2; Msg.Buffer.Size := 2; Msg.Buffer.Current := Msg.Buffer.Start; Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer)); if Msg.Size < 2 then Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size)); end if; if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Data'Last then Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size)); exit; end if; Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last); Msg.Buffer.Current := Msg.Buffer.Start; Msg.Buffer.Last := Data (Last)'Address; Msg.Buffer.Size := Msg.Size; Reader.Dispatch_Message (Msg); end loop; end Read_All; end MAT.Readers.Files;
----------------------------------------------------------------------- -- mat-readers-files -- Reader for files -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams.Stream_IO; with Util.Log.Loggers; with MAT.Readers.Marshaller; package body MAT.Readers.Files is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files"); -- Open the file. procedure Open (Reader : in out File_Reader_Type; Path : in String) is begin Log.Info ("Reading data stream {0}", Path); Reader.Stream.Initialize (Size => BUFFER_SIZE, Input => Reader.File'Unchecked_Access, Output => null); Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => Path); end Open; end MAT.Readers.Files;
Remove the Read_All procedure which is now defined by MAT.Readers.Streams package
Remove the Read_All procedure which is now defined by MAT.Readers.Streams package
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
80239da730ec6c91086aceaf0dfbb6a914fff2ea
src/util-texts-transforms.adb
src/util-texts-transforms.adb
----------------------------------------------------------------------- -- Util-texts -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; package body Util.Texts.Transforms is type Code is mod 2**32; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; procedure Put_Dec (Into : in out Stream; Value : in Code); procedure To_Hex (Into : in out Stream; Value : in Code); procedure Put (Into : in out Stream; Value : in String) is begin for I in Value'Range loop Put (Into, Value (I)); end loop; end Put; -- ------------------------------ -- Write in the output stream the value as a \uNNNN encoding form. -- ------------------------------ procedure To_Hex (Into : in out Stream; Value : in Char) is begin To_Hex (Into, Code (Char'Pos (Value))); end To_Hex; -- ------------------------------ -- Write in the output stream the value as a \uNNNN encoding form. -- ------------------------------ procedure To_Hex (Into : in out Stream; Value : in Code) is S : String (1 .. 6) := (1 => '\', 2 => 'u', others => '0'); P : Code := Value; N : Code; I : Positive := S'Last; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Positive'Val (N + 1)); exit when I = 1; I := I - 1; end loop; Put (Into, S); end To_Hex; procedure Put_Dec (Into : in out Stream; Value : in Code) is S : String (1 .. 9) := (others => '0'); P : Code := Value; N : Code; I : Positive := S'Last; begin while P /= 0 loop N := P mod 10; P := P / 10; S (I) := Conversion (Positive'Val (N + 1)); exit when P = 0; I := I - 1; end loop; Put (Into, S (I .. S'Last)); end Put_Dec; -- ------------------------------ -- Capitalize the string into the result stream. -- ------------------------------ procedure Capitalize (Content : in Input; Into : in out Stream) is Upper : Boolean := True; C : Code; begin for I in Content'Range loop if Upper then C := Char'Pos (To_Upper (Content (I))); Upper := False; else C := Char'Pos (To_Lower (Content (I))); if C = Character'Pos ('_') or C = Character'Pos ('.') or C = Character'Pos (':') or C = Character'Pos (';') or C = Character'Pos (',') or C = Character'Pos (' ') then Upper := True; end if; end if; Put (Into, Character'Val (C)); end loop; end Capitalize; -- ------------------------------ -- Capitalize the string -- ------------------------------ function Capitalize (Content : Input) return Input is Upper : Boolean := True; C : Code; Result : Input (Content'Range); begin for I in Content'Range loop if Upper then C := Char'Pos (To_Upper (Content (I))); Upper := False; else C := Char'Pos (To_Lower (Content (I))); if C = Character'Pos ('_') or C = Character'Pos ('.') or C = Character'Pos (':') or C = Character'Pos (';') or C = Character'Pos (',') or C = Character'Pos (' ') then Upper := True; end if; end if; Result (I) := Char'Val (C); end loop; return Result; end Capitalize; -- ------------------------------ -- Translate the input string into an upper case string in the result stream. -- ------------------------------ procedure To_Upper_Case (Content : in Input; Into : in out Stream) is C : Code; begin for I in Content'Range loop C := Char'Pos (To_Upper (Content (I))); Put (Into, Character'Val (C)); end loop; end To_Upper_Case; -- ------------------------------ -- Translate the input string into an upper case string. -- ------------------------------ function To_Upper_Case (Content : Input) return Input is Result : Input (Content'Range); begin for I in Content'Range loop Result (I) := To_Upper (Content (I)); end loop; return Result; end To_Upper_Case; -- ------------------------------ -- Translate the input string into a lower case string in the result stream. -- ------------------------------ procedure To_Lower_Case (Content : in Input; Into : in out Stream) is C : Code; begin for I in Content'Range loop C := Char'Pos (To_Lower (Content (I))); Put (Into, Character'Val (C)); end loop; end To_Lower_Case; -- ------------------------------ -- Translate the input string into a lower case string in the result stream. -- ------------------------------ function To_Lower_Case (Content : Input) return Input is Result : Input (Content'Range); begin for I in Content'Range loop Result (I) := To_Lower (Content (I)); end loop; return Result; end To_Lower_Case; procedure Escape_Java_Script (Content : in Input; Into : in out Stream) is begin Escape_Java (Content => Content, Into => Into, Escape_Single_Quote => True); end Escape_Java_Script; procedure Escape_Java (Content : in Input; Into : in out Stream) is begin Escape_Java (Content => Content, Into => Into, Escape_Single_Quote => False); end Escape_Java; procedure Escape_Java (Content : in Input; Escape_Single_Quote : in Boolean; Into : in out Stream) is C : Code; begin for I in Content'Range loop C := Char'Pos (Content (I)); if C < 16#20# then if C = 16#0A# then Put (Into, '\'); Put (Into, 'n'); elsif C = 16#0D# then Put (Into, '\'); Put (Into, 'r'); elsif C = 16#08# then Put (Into, '\'); Put (Into, 'b'); elsif C = 16#09# then Put (Into, '\'); Put (Into, 't'); elsif C = 16#0C# then Put (Into, '\'); Put (Into, 'f'); else To_Hex (Into, C); end if; elsif C = 16#27# then if Escape_Single_Quote then Put (Into, '\'); end if; Put (Into, Character'Val (C)); elsif C = 16#22# then Put (Into, '\'); Put (Into, Character'Val (C)); elsif C = 16#5C# then Put (Into, '\'); Put (Into, Character'Val (C)); elsif C >= 16#100# then To_Hex (Into, C); else Put (Into, Character'Val (C)); end if; end loop; end Escape_Java; -- ------------------------------ -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 -- ------------------------------ procedure Escape_Xml (Content : in Input; Into : in out Stream) is C : Code; begin for I in Content'Range loop C := Char'Pos (Content (I)); if C = Character'Pos ('<') then Put (Into, "&lt;"); elsif C = Character'Pos ('>') then Put (Into, "&gt;"); elsif C = Character'Pos ('&') then Put (Into, "&amp;"); elsif C = Character'Pos (''') then Put (Into, "&apos;"); elsif C > 16#7F# then Put (Into, '&'); Put (Into, '#'); Put_Dec (Into, C); Put (Into, ';'); else Put (Into, Character'Val (C)); end if; end loop; end Escape_Xml; -- ------------------------------ -- Translate the XML entity represented by <tt>Entity</tt> into an UTF-8 sequence -- in the output stream. -- ------------------------------ procedure Translate_Xml_Entity (Entity : in Input; Into : in out Stream) is begin if Entity (Entity'First) = Char'Val (Character'Pos ('&')) and then Entity (Entity'Last) = Char'Val (Character'Pos (';')) then case Char'Pos (Entity (Entity'First + 1)) is when Character'Pos ('l') => if Entity'Length = 4 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('t')) then Put (Into, '<'); return; end if; when Character'Pos ('g') => if Entity'Length = 4 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('t')) then Put (Into, '>'); return; end if; when Character'Pos ('a') => if Entity'Length = 5 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('m')) and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('p')) then Put (Into, '&'); return; end if; if Entity'Length = 6 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('p')) and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('o')) and then Entity (Entity'First + 4) = Char'Val (Character'Pos ('s')) then Put (Into, '''); return; end if; when Character'Pos ('q') => if Entity'Length = 6 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('u')) and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('o')) and then Entity (Entity'First + 4) = Char'Val (Character'Pos ('t')) then Put (Into, '"'); return; end if; when Character'Pos ('#') => declare use Interfaces; V : Unsigned_32 := 0; C : Code; begin if Entity (Entity'First + 2) = Char'Val (Character'Pos ('x')) then for I in Entity'First + 3 .. Entity'Last - 1 loop C := Char'Pos (Entity (I)); if C >= Character'Pos ('0') and C <= Character'Pos ('9') then V := (V * 16) + Unsigned_32 (C - Character'Pos ('0')); elsif C >= Character'Pos ('a') and C <= Character'Pos ('z') then V := (V * 16) + 10 + Unsigned_32 (C - Character'Pos ('a')); elsif C >= Character'Pos ('A') and C <= Character'Pos ('Z') then V := (V * 16) + 10 + Unsigned_32 (C - Character'Pos ('A')); end if; end loop; else for I in Entity'First + 2 .. Entity'Last - 1 loop C := Char'Pos (Entity (I)); if C >= Character'Pos ('0') and C <= Character'Pos ('9') then V := (V * 10) + Unsigned_32 (C - Character'Pos ('0')); end if; end loop; end if; if V <= 16#007F# then Put (Into, Character'Val (V)); return; elsif V <= 16#07FF# then Put (Into, Character'Val (16#C0# or Interfaces.Shift_Right (V, 6))); Put (Into, Character'Val (16#80# or (V and 16#03F#))); return; elsif V <= 16#0FFFF# then Put (Into, Character'Val (16#D0# or Shift_Right (V, 12))); Put (Into, Character'Val (16#80# or (Shift_Right (V, 6) and 16#03F#))); Put (Into, Character'Val (16#80# or (V and 16#03F#))); return; elsif V <= 16#10FFFF# then Put (Into, Character'Val (16#E0# or Shift_Right (V, 18))); Put (Into, Character'Val (16#80# or (Shift_Right (V, 12) and 16#03F#))); Put (Into, Character'Val (16#80# or (Shift_Right (V, 6) and 16#03F#))); Put (Into, Character'Val (16#80# or (V and 16#03F#))); return; end if; end; when others => null; end case; end if; -- Invalid entity. end Translate_Xml_Entity; -- ------------------------------ -- Unescape the XML entities from the content into the result stream. -- For each XML entity found, call the <tt>Translator</tt> procedure who is responsible -- for writing the result in the stream. The XML entity starts with '&' and ends with ';'. -- The '&' and ';' are part of the entity when given to the translator. If the trailing -- ';' is not part of the entity, it means the entity was truncated or the end of input -- stream is reached. -- ------------------------------ procedure Unescape_Xml (Content : in Input; Translator : not null access procedure (Entity : in Input; Into : in out Stream) := Translate_Xml_Entity'Access; Into : in out Stream) is MAX_ENTITY_LENGTH : constant Positive := 30; Entity : Input (1 .. MAX_ENTITY_LENGTH); C : Code; Pos : Natural := Content'First; Last : Natural; begin while Pos <= Content'Last loop C := Char'Pos (Content (Pos)); Pos := Pos + 1; if C = Character'Pos ('&') then Entity (Entity'First) := Char'Val (C); Last := Entity'First; while Pos <= Content'Last loop C := Char'Pos (Content (Pos)); Pos := Pos + 1; if Last < Entity'Last then Last := Last + 1; Entity (Last) := Char'Val (C); end if; exit when C = Character'Pos (';'); end loop; Translator (Entity (Entity'First .. Last), Into); else Put (Into, Character'Val (C)); end if; end loop; end Unescape_Xml; end Util.Texts.Transforms;
----------------------------------------------------------------------- -- util-texts-transforms -- Various Text Transformation Utilities -- Copyright (C) 2001, 2002, 2003, 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 Interfaces; package body Util.Texts.Transforms is type Code is mod 2**32; Conversion : constant String (1 .. 16) := "0123456789ABCDEF"; procedure Put_Dec (Into : in out Stream; Value : in Code); procedure To_Hex (Into : in out Stream; Value : in Code); procedure Put (Into : in out Stream; Value : in String) is begin for I in Value'Range loop Put (Into, Value (I)); end loop; end Put; -- ------------------------------ -- Write in the output stream the value as a \uNNNN encoding form. -- ------------------------------ procedure To_Hex (Into : in out Stream; Value : in Char) is begin To_Hex (Into, Code (Char'Pos (Value))); end To_Hex; -- ------------------------------ -- Write in the output stream the value as a \uNNNN encoding form. -- ------------------------------ procedure To_Hex (Into : in out Stream; Value : in Code) is S : String (1 .. 6) := (1 => '\', 2 => 'u', others => '0'); P : Code := Value; N : Code; I : Positive := S'Last; begin while P /= 0 loop N := P mod 16; P := P / 16; S (I) := Conversion (Positive'Val (N + 1)); exit when I = 1; I := I - 1; end loop; Put (Into, S); end To_Hex; procedure Put_Dec (Into : in out Stream; Value : in Code) is S : String (1 .. 9) := (others => '0'); P : Code := Value; N : Code; I : Positive := S'Last; begin while P /= 0 loop N := P mod 10; P := P / 10; S (I) := Conversion (Positive'Val (N + 1)); exit when P = 0; I := I - 1; end loop; Put (Into, S (I .. S'Last)); end Put_Dec; -- ------------------------------ -- Capitalize the string into the result stream. -- ------------------------------ procedure Capitalize (Content : in Input; Into : in out Stream) is Upper : Boolean := True; C : Code; begin for I in Content'Range loop if Upper then C := Char'Pos (To_Upper (Content (I))); Upper := False; else C := Char'Pos (To_Lower (Content (I))); if C = Character'Pos ('_') or C = Character'Pos ('.') or C = Character'Pos (':') or C = Character'Pos (';') or C = Character'Pos (',') or C = Character'Pos (' ') then Upper := True; end if; end if; Put (Into, Character'Val (C)); end loop; end Capitalize; -- ------------------------------ -- Capitalize the string -- ------------------------------ function Capitalize (Content : Input) return Input is Upper : Boolean := True; C : Code; Result : Input (Content'Range); begin for I in Content'Range loop if Upper then C := Char'Pos (To_Upper (Content (I))); Upper := False; else C := Char'Pos (To_Lower (Content (I))); if C = Character'Pos ('_') or C = Character'Pos ('.') or C = Character'Pos (':') or C = Character'Pos (';') or C = Character'Pos (',') or C = Character'Pos (' ') then Upper := True; end if; end if; Result (I) := Char'Val (C); end loop; return Result; end Capitalize; -- ------------------------------ -- Translate the input string into an upper case string in the result stream. -- ------------------------------ procedure To_Upper_Case (Content : in Input; Into : in out Stream) is C : Code; begin for I in Content'Range loop C := Char'Pos (To_Upper (Content (I))); Put (Into, Character'Val (C)); end loop; end To_Upper_Case; -- ------------------------------ -- Translate the input string into an upper case string. -- ------------------------------ function To_Upper_Case (Content : Input) return Input is Result : Input (Content'Range); begin for I in Content'Range loop Result (I) := To_Upper (Content (I)); end loop; return Result; end To_Upper_Case; -- ------------------------------ -- Translate the input string into a lower case string in the result stream. -- ------------------------------ procedure To_Lower_Case (Content : in Input; Into : in out Stream) is C : Code; begin for I in Content'Range loop C := Char'Pos (To_Lower (Content (I))); Put (Into, Character'Val (C)); end loop; end To_Lower_Case; -- ------------------------------ -- Translate the input string into a lower case string in the result stream. -- ------------------------------ function To_Lower_Case (Content : Input) return Input is Result : Input (Content'Range); begin for I in Content'Range loop Result (I) := To_Lower (Content (I)); end loop; return Result; end To_Lower_Case; procedure Escape_Java_Script (Content : in Input; Into : in out Stream) is begin Escape_Java (Content => Content, Into => Into, Escape_Single_Quote => True); end Escape_Java_Script; procedure Escape_Java (Content : in Input; Into : in out Stream) is begin Escape_Java (Content => Content, Into => Into, Escape_Single_Quote => False); end Escape_Java; procedure Escape_Java (Content : in Input; Escape_Single_Quote : in Boolean; Into : in out Stream) is C : Code; begin for I in Content'Range loop C := Char'Pos (Content (I)); if C < 16#20# then if C = 16#0A# then Put (Into, '\'); Put (Into, 'n'); elsif C = 16#0D# then Put (Into, '\'); Put (Into, 'r'); elsif C = 16#08# then Put (Into, '\'); Put (Into, 'b'); elsif C = 16#09# then Put (Into, '\'); Put (Into, 't'); elsif C = 16#0C# then Put (Into, '\'); Put (Into, 'f'); else To_Hex (Into, C); end if; elsif C = 16#27# then if Escape_Single_Quote then Put (Into, '\'); end if; Put (Into, Character'Val (C)); elsif C = 16#22# then Put (Into, '\'); Put (Into, Character'Val (C)); elsif C = 16#5C# then Put (Into, '\'); Put (Into, Character'Val (C)); elsif C >= 16#100# then To_Hex (Into, C); else Put (Into, Character'Val (C)); end if; end loop; end Escape_Java; -- ------------------------------ -- Escape the content into the result stream using the XML -- escape rules: -- '<' -> '&lt;' -- '>' -> '&gt;' -- ''' -> '&apos;' -- '&' -> '&amp;' -- -> '&#nnn;' if Character'Pos >= 128 -- ------------------------------ procedure Escape_Xml (Content : in Input; Into : in out Stream) is C : Code; begin for I in Content'Range loop C := Char'Pos (Content (I)); if C = Character'Pos ('<') then Put (Into, "&lt;"); elsif C = Character'Pos ('>') then Put (Into, "&gt;"); elsif C = Character'Pos ('&') then Put (Into, "&amp;"); elsif C = Character'Pos (''') then Put (Into, "&apos;"); elsif C > 16#7F# then Put (Into, '&'); Put (Into, '#'); Put_Dec (Into, C); Put (Into, ';'); else Put (Into, Character'Val (C)); end if; end loop; end Escape_Xml; -- ------------------------------ -- Translate the XML entity represented by <tt>Entity</tt> into an UTF-8 sequence -- in the output stream. -- ------------------------------ procedure Translate_Xml_Entity (Entity : in Input; Into : in out Stream) is begin if Entity (Entity'First) = Char'Val (Character'Pos ('&')) and then Entity (Entity'Last) = Char'Val (Character'Pos (';')) then case Char'Pos (Entity (Entity'First + 1)) is when Character'Pos ('l') => if Entity'Length = 4 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('t')) then Put (Into, '<'); return; end if; when Character'Pos ('g') => if Entity'Length = 4 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('t')) then Put (Into, '>'); return; end if; when Character'Pos ('a') => if Entity'Length = 5 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('m')) and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('p')) then Put (Into, '&'); return; end if; if Entity'Length = 6 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('p')) and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('o')) and then Entity (Entity'First + 4) = Char'Val (Character'Pos ('s')) then Put (Into, '''); return; end if; when Character'Pos ('q') => if Entity'Length = 6 and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('u')) and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('o')) and then Entity (Entity'First + 4) = Char'Val (Character'Pos ('t')) then Put (Into, '"'); return; end if; when Character'Pos ('#') => declare use Interfaces; V : Unsigned_32 := 0; C : Code; begin if Entity (Entity'First + 2) = Char'Val (Character'Pos ('x')) then for I in Entity'First + 3 .. Entity'Last - 1 loop C := Char'Pos (Entity (I)); if C >= Character'Pos ('0') and C <= Character'Pos ('9') then V := (V * 16) + Unsigned_32 (C - Character'Pos ('0')); elsif C >= Character'Pos ('a') and C <= Character'Pos ('z') then V := (V * 16) + 10 + Unsigned_32 (C - Character'Pos ('a')); elsif C >= Character'Pos ('A') and C <= Character'Pos ('Z') then V := (V * 16) + 10 + Unsigned_32 (C - Character'Pos ('A')); end if; end loop; else for I in Entity'First + 2 .. Entity'Last - 1 loop C := Char'Pos (Entity (I)); if C >= Character'Pos ('0') and C <= Character'Pos ('9') then V := (V * 10) + Unsigned_32 (C - Character'Pos ('0')); end if; end loop; end if; if V <= 16#007F# then Put (Into, Character'Val (V)); return; elsif V <= 16#07FF# then Put (Into, Character'Val (16#C0# or Interfaces.Shift_Right (V, 6))); Put (Into, Character'Val (16#80# or (V and 16#03F#))); return; elsif V <= 16#0FFFF# then Put (Into, Character'Val (16#D0# or Shift_Right (V, 12))); Put (Into, Character'Val (16#80# or (Shift_Right (V, 6) and 16#03F#))); Put (Into, Character'Val (16#80# or (V and 16#03F#))); return; elsif V <= 16#10FFFF# then Put (Into, Character'Val (16#E0# or Shift_Right (V, 18))); Put (Into, Character'Val (16#80# or (Shift_Right (V, 12) and 16#03F#))); Put (Into, Character'Val (16#80# or (Shift_Right (V, 6) and 16#03F#))); Put (Into, Character'Val (16#80# or (V and 16#03F#))); return; end if; end; when others => null; end case; end if; -- Invalid entity. end Translate_Xml_Entity; -- ------------------------------ -- Unescape the XML entities from the content into the result stream. -- For each XML entity found, call the <tt>Translator</tt> procedure who is responsible -- for writing the result in the stream. The XML entity starts with '&' and ends with ';'. -- The '&' and ';' are part of the entity when given to the translator. If the trailing -- ';' is not part of the entity, it means the entity was truncated or the end of input -- stream is reached. -- ------------------------------ procedure Unescape_Xml (Content : in Input; Translator : not null access procedure (Entity : in Input; Into : in out Stream) := Translate_Xml_Entity'Access; Into : in out Stream) is MAX_ENTITY_LENGTH : constant Positive := 30; Entity : Input (1 .. MAX_ENTITY_LENGTH); C : Code; Pos : Natural := Content'First; Last : Natural; begin while Pos <= Content'Last loop C := Char'Pos (Content (Pos)); Pos := Pos + 1; if C = Character'Pos ('&') then Entity (Entity'First) := Char'Val (C); Last := Entity'First; while Pos <= Content'Last loop C := Char'Pos (Content (Pos)); Pos := Pos + 1; if Last < Entity'Last then Last := Last + 1; Entity (Last) := Char'Val (C); end if; exit when C = Character'Pos (';'); end loop; Translator (Entity (Entity'First .. Last), Into); else Put (Into, Character'Val (C)); end if; end loop; end Unescape_Xml; end Util.Texts.Transforms;
Fix the header
Fix the header
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
72e682e53e17bc845227c9b60d8a6bb847988b46
src/ado-sessions-sources.ads
src/ado-sessions-sources.ads
----------------------------------------------------------------------- -- ado-sessions-sources -- Database Sources -- 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. ----------------------------------------------------------------------- package ADO.Sessions.Sources is -- ------------------------------ -- The database connection source -- ------------------------------ -- The <b>DataSource</b> is the factory for getting a connection to the database. -- It contains the configuration properties to define which database driver must -- be used and which connection parameters the driver has to use to establish -- the connection. type Data_Source is new ADO.Drivers.Connections.Configuration with private; type Data_Source_Access is access all Data_Source'Class; -- Attempts to establish a connection with the data source -- that this Data_Source object represents. -- procedure Create_Connection (Controller : in Data_Source) -- return ADO.Master_Connection'Class; -- ------------------------------ -- Replicated Data Source -- ------------------------------ -- The replicated data source supports a Master/Slave database configuration. -- When using this data source, the master is used to execute -- update, insert, delete and also query statements. The slave is used -- to execute query statements. The master and slave are represented by -- two separate data sources. This allows to have a master on one server, -- use a specific user/password and get a slave on another server with other -- credentials. type Replicated_DataSource is new Data_Source with private; type Replicated_DataSource_Access is access all Replicated_DataSource'Class; -- Set the master data source procedure Set_Master (Controller : in out Replicated_DataSource; Master : in Data_Source_Access); -- Get the master data source function Get_Master (Controller : in Replicated_DataSource) return Data_Source_Access; -- Set the slave data source procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in Data_Source_Access); -- Get the slace data source function Get_Slave (Controller : in Replicated_DataSource) return Data_Source_Access; -- Get a slave database connection -- function Get_Slave_Connection (Controller : in Replicated_DataSource) -- return Connection'Class; private type Data_Source is new ADO.Drivers.Connections.Configuration with null record; type Replicated_DataSource is new Data_Source with record Master : Data_Source_Access := null; Slave : Data_Source_Access := null; end record; end ADO.Sessions.Sources;
----------------------------------------------------------------------- -- ado-sessions-sources -- Database Sources -- 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. ----------------------------------------------------------------------- -- == Connection string == -- The database connection string is an URI that specifies the database driver to use as well -- as the information for the database driver to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- The database connection string is passed to the session factory that maintains connections -- to the database (see ADO.Sessions.Factory). -- package ADO.Sessions.Sources is -- ------------------------------ -- The database connection source -- ------------------------------ -- The <b>DataSource</b> is the factory for getting a connection to the database. -- It contains the configuration properties to define which database driver must -- be used and which connection parameters the driver has to use to establish -- the connection. type Data_Source is new ADO.Drivers.Connections.Configuration with private; type Data_Source_Access is access all Data_Source'Class; -- Attempts to establish a connection with the data source -- that this Data_Source object represents. -- procedure Create_Connection (Controller : in Data_Source) -- return ADO.Master_Connection'Class; -- ------------------------------ -- Replicated Data Source -- ------------------------------ -- The replicated data source supports a Master/Slave database configuration. -- When using this data source, the master is used to execute -- update, insert, delete and also query statements. The slave is used -- to execute query statements. The master and slave are represented by -- two separate data sources. This allows to have a master on one server, -- use a specific user/password and get a slave on another server with other -- credentials. type Replicated_DataSource is new Data_Source with private; type Replicated_DataSource_Access is access all Replicated_DataSource'Class; -- Set the master data source procedure Set_Master (Controller : in out Replicated_DataSource; Master : in Data_Source_Access); -- Get the master data source function Get_Master (Controller : in Replicated_DataSource) return Data_Source_Access; -- Set the slave data source procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in Data_Source_Access); -- Get the slace data source function Get_Slave (Controller : in Replicated_DataSource) return Data_Source_Access; -- Get a slave database connection -- function Get_Slave_Connection (Controller : in Replicated_DataSource) -- return Connection'Class; private type Data_Source is new ADO.Drivers.Connections.Configuration with null record; type Replicated_DataSource is new Data_Source with record Master : Data_Source_Access := null; Slave : Data_Source_Access := null; end record; end ADO.Sessions.Sources;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-ado
c991a44fa01c1ca0e5dbd23c5cbe307d752b4390
src/asf-components-utils.adb
src/asf-components-utils.adb
----------------------------------------------------------------------- -- components-util -- ASF Util Components -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views; with ASF.Views.Nodes; package body ASF.Components.Utils is function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info; -- ------------------------------ -- Get the line information where the component is defined. -- ------------------------------ function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info is Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag; begin if Tag /= null then return Tag.Get_Line_Info; else return Tag.Get_Line_Info; end if; end Get_Line_Info; pragma Unreferenced (Get_Line_Info); -- ------------------------------ -- Get the line information where the component is defined. -- ------------------------------ function Get_Line_Info (UI : in Base.UIComponent'Class) return String is Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag; begin if Tag /= null then return Tag.Get_Line_Info; else return Tag.Get_Line_Info; end if; end Get_Line_Info; end ASF.Components.Utils;
----------------------------------------------------------------------- -- components-util -- ASF Util Components -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Views; with ASF.Views.Nodes; package body ASF.Components.Utils is function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info; -- ------------------------------ -- Get the line information where the component is defined. -- ------------------------------ function Get_Line_Info (UI : in Base.UIComponent'Class) return Views.Line_Info is Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag; begin if Tag /= null then return Tag.Get_Line_Info; else return Tag.Get_Line_Info; end if; end Get_Line_Info; pragma Unreferenced (Get_Line_Info); -- ------------------------------ -- Get the line information where the component is defined. -- ------------------------------ function Get_Line_Info (UI : in Base.UIComponent'Class) return String is Tag : constant access ASF.Views.Nodes.Tag_Node'Class := UI.Get_Tag; begin if Tag /= null then return Tag.Get_Line_Info; else return "?"; end if; end Get_Line_Info; end ASF.Components.Utils;
Fix exception in case the component has no associated tag
Fix exception in case the component has no associated tag
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
aa02552f0c12d01ba0b9e63ca22d6d562611a000
src/gen-commands-propset.ads
src/gen-commands-propset.ads
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Propset is -- ------------------------------ -- Propset Command -- ------------------------------ -- This command sets a property in the dynamo project configuration. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out 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.Propset;
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Gen.Commands.Propset is -- ------------------------------ -- Propset Command -- ------------------------------ -- This command sets a property in the dynamo project configuration. type Command is new Gen.Commands.Command with null record; -- Execute the command with the arguments. overriding procedure Execute (Cmd : in out 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 out Command; Generator : in out Gen.Generator.Handler); end Gen.Commands.Propset;
Update to use an in out parameter for Help procedure
Update to use an in out parameter for Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
bfb91b395ea0ed6b16ae1d0bd06f7711e03e0bf8
src/gen-model-operations.adb
src/gen-model-operations.adb
----------------------------------------------------------------------- -- gen-model-operations -- Operation declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.Operations is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Operation_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "parameters" or Name = "columns" then return From.Parameters_Bean; elsif Name = "return" then return Util.Beans.Objects.To_Object (From.Return_Type); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Operation_Definition) is begin null; end Prepare; -- ------------------------------ -- Initialize the operation definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Operation_Definition) is begin O.Parameters_Bean := Util.Beans.Objects.To_Object (O.Parameters'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an operation parameter with the given name and type. -- ------------------------------ procedure Add_Parameter (Into : in out Operation_Definition; Name : in Unbounded_String; Of_Type : in Unbounded_String; Parameter : out Parameter_Definition_Access) is begin Parameter := new Parameter_Definition; Parameter.Name := Name; Parameter.Type_Name := Of_Type; Into.Parameters.Append (Parameter); end Add_Parameter; -- ------------------------------ -- Create an operation with the given name. -- ------------------------------ function Create_Operation (Name : in Unbounded_String) return Operation_Definition_Access is Result : constant Operation_Definition_Access := new Operation_Definition; begin return Result; end Create_Operation; end Gen.Model.Operations;
----------------------------------------------------------------------- -- gen-model-operations -- Operation declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Model.Operations is -- ------------------------------ -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. -- ------------------------------ overriding function Get_Value (From : in Operation_Definition; Name : in String) return Util.Beans.Objects.Object is begin if Name = "parameters" or Name = "columns" then return From.Parameters_Bean; elsif Name = "return" then return Util.Beans.Objects.To_Object (From.Return_Type); else return Definition (From).Get_Value (Name); end if; end Get_Value; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Operation_Definition) is begin null; end Prepare; -- ------------------------------ -- Initialize the operation definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Operation_Definition) is begin O.Parameters_Bean := Util.Beans.Objects.To_Object (O.Parameters'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an operation parameter with the given name and type. -- ------------------------------ procedure Add_Parameter (Into : in out Operation_Definition; Name : in Unbounded_String; Of_Type : in Unbounded_String; Parameter : out Parameter_Definition_Access) is begin Parameter := new Parameter_Definition; Parameter.Name := Name; Parameter.Type_Name := Of_Type; Into.Parameters.Append (Parameter); end Add_Parameter; -- ------------------------------ -- Create an operation with the given name. -- ------------------------------ function Create_Operation (Name : in Unbounded_String) return Operation_Definition_Access is pragma Unreferenced (Name); Result : constant Operation_Definition_Access := new Operation_Definition; begin return Result; end Create_Operation; end Gen.Model.Operations;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
88991bc91dc302d52b7f6c87897b7579a4f13133
arch/ARM/Nordic/drivers/nrf51-temperature.ads
arch/ARM/Nordic/drivers/nrf51-temperature.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, 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. -- -- -- ------------------------------------------------------------------------------ package nRF51.Temperature is type Temp_Celcius is delta 0.25 range -2_147_483_648.0 / 4 .. 2_147_483_647.0 / 4; function Read return Temp_Celcius; end nRF51.Temperature;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, 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. -- -- -- ------------------------------------------------------------------------------ package nRF51.Temperature is type Temp_Celsius is delta 0.25 range -2_147_483_648.0 / 4 .. 2_147_483_647.0 / 4; function Read return Temp_Celsius; end nRF51.Temperature;
Update nrf51-temperature.ads
Update nrf51-temperature.ads
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
590a1f47b13745bfad83876b1ca980c2ba82d747
jack-client.ads
jack-client.ads
with Ada.Containers.Ordered_Sets; with Ada.Strings.Bounded; with Ada.Unchecked_Deallocation; with Jack.Thin; with System; pragma Elaborate_All (Jack.Thin); package Jack.Client is -- -- Types. -- type Number_Of_Frames_t is new Thin.Number_Of_Frames_t; -- -- Options -- type Option_Selector_t is (Do_Not_Start_Server, Use_Exact_Name, Server_Name, Load_Name, Load_Initialize); type Options_t is array (Option_Selector_t) of Boolean; -- -- Status -- type Status_Selector_t is (Failure, Invalid_Option, Name_Not_Unique, Server_Started, Server_Failed, Server_Error, No_Such_Client, Load_Failure, Init_Failure, Shared_Memory_Failure, Version_Error); type Status_t is array (Status_Selector_t) of Boolean; -- -- Port flags -- type Port_Flag_Selector_t is (Port_Is_Input, Port_Is_Output, Port_Is_Physical, Port_Can_Monitor, Port_Is_Terminal); type Port_Flags_t is array (Port_Flag_Selector_t) of Boolean; -- -- Client -- type Client_t is limited private; Invalid_Client : constant Client_t; function Compare (Left : in Client_t; Right : in Client_t) return Boolean; function "=" (Left : in Client_t; Right : in Client_t) return Boolean renames Compare; -- -- Port -- type Port_t is limited private; Invalid_Port : constant Port_t; -- -- Port name -- subtype Port_Name_Size_t is Natural range 0 .. Natural (Thin.Port_Name_Size); subtype Port_Name_Index_t is Port_Name_Size_t range 1 .. Port_Name_Size_t'Last; package Port_Names is new Ada.Strings.Bounded.Generic_Bounded_Length (Port_Name_Index_t'Last); subtype Port_Name_t is Port_Names.Bounded_String; package Port_Name_Sets is new Ada.Containers.Ordered_Sets (Element_Type => Port_Name_t, "=" => Port_Names."=", "<" => Port_Names."<"); subtype Port_Name_Set_t is Port_Name_Sets.Set; -- -- API -- -- proc_map : jack_client_close procedure Close (Client : in Client_t; Failed : out Boolean); -- proc_map : jack_connect procedure Connect (Client : in Client_t; Source_Port : in Port_Name_t; Destination_Port : in Port_Name_t; Failed : out Boolean); -- proc_map : jack_disconnect procedure Disconnect (Client : in Client_t; Source_Port : in Port_Name_t; Destination_Port : in Port_Name_t; Failed : out Boolean); -- proc_map : jack_client_open procedure Open (Client_Name : in String; Options : in Options_t; Client : out Client_t; Status : in out Status_t); -- proc_map : jack_port_register procedure Port_Register (Client : in Client_t; Port : out Port_t; Port_Name : in Port_Name_t; Port_Type : in String; Port_Flags : in Port_Flags_t; Buffer_Size : in Natural := 0); -- proc_map : jack_activate procedure Activate (Client : in Client_t; Failed : out Boolean); -- proc_map : jack_get_ports procedure Get_Ports (Client : in Client_t; Port_Name_Pattern : in String; Port_Type_Pattern : in String; Port_Flags : in Port_Flags_t; Ports : out Port_Name_Set_t); generic type User_Data_Type is private; type User_Data_Access_Type is access User_Data_Type; package Generic_Callbacks is type Process_Callback_State_t is record Callback : access procedure (Number_Of_Frames : in Number_Of_Frames_t; User_Data : in User_Data_Access_Type); User_Data : User_Data_Access_Type; end record; type Process_Callback_State_Access_t is access Process_Callback_State_t; procedure Deallocate_State is new Ada.Unchecked_Deallocation (Object => User_Data_Type, Name => User_Data_Access_Type); -- proc_map : jack_set_process_callback procedure Set_Process_Callback (Client : in Client_t; State : in Process_Callback_State_Access_t; Failed : out Boolean); end Generic_Callbacks; -- -- Private -- function To_Address (Client : in Client_t) return System.Address; pragma Inline (To_Address); function To_Address (Port : in Port_t) return System.Address; pragma Inline (To_Address); private type Client_t is new System.Address; type Port_t is new System.Address; Invalid_Client : constant Client_t := Client_t (System.Null_Address); Invalid_Port : constant Port_t := Port_t (System.Null_Address); function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t; pragma Inline (Map_Status_To_Thin); function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t; pragma Inline (Map_Thin_To_Status); function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t; pragma Inline (Map_Options_To_Thin); function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t; pragma Inline (Map_Thin_To_Options); function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t; pragma Inline (Map_Port_Flags_To_Thin); function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t; pragma Inline (Map_Thin_To_Port_Flags); end Jack.Client;
with Ada.Containers.Ordered_Sets; with Ada.Strings.Bounded; with Ada.Unchecked_Deallocation; with Jack.Thin; with System; pragma Elaborate_All (Jack.Thin); package Jack.Client is -- -- Types. -- type Number_Of_Frames_t is new Thin.Number_Of_Frames_t; -- -- Options -- type Option_Selector_t is (Do_Not_Start_Server, Use_Exact_Name, Server_Name, Load_Name, Load_Initialize); type Options_t is array (Option_Selector_t) of Boolean; -- -- Status -- type Status_Selector_t is (Failure, Invalid_Option, Name_Not_Unique, Server_Started, Server_Failed, Server_Error, No_Such_Client, Load_Failure, Init_Failure, Shared_Memory_Failure, Version_Error); type Status_t is array (Status_Selector_t) of Boolean; -- -- Port flags -- type Port_Flag_Selector_t is (Port_Is_Input, Port_Is_Output, Port_Is_Physical, Port_Can_Monitor, Port_Is_Terminal); type Port_Flags_t is array (Port_Flag_Selector_t) of Boolean; -- -- Client -- type Client_t is limited private; Invalid_Client : constant Client_t; function Compare (Left : in Client_t; Right : in Client_t) return Boolean; function "=" (Left : in Client_t; Right : in Client_t) return Boolean renames Compare; -- -- Port -- type Port_t is limited private; Invalid_Port : constant Port_t; -- -- Port name -- subtype Port_Name_Size_t is Natural range 0 .. Natural (Thin.Port_Name_Size); subtype Port_Name_Index_t is Port_Name_Size_t range 1 .. Port_Name_Size_t'Last; package Port_Names is new Ada.Strings.Bounded.Generic_Bounded_Length (Port_Name_Index_t'Last); subtype Port_Name_t is Port_Names.Bounded_String; package Port_Name_Sets is new Ada.Containers.Ordered_Sets (Element_Type => Port_Name_t, "=" => Port_Names."=", "<" => Port_Names."<"); subtype Port_Name_Set_t is Port_Name_Sets.Set; Default_Audio_Type : constant Port_Name_t := Port_Names.To_Bounded_String ("32 bit float mono audio"); -- -- API -- -- proc_map : jack_client_close procedure Close (Client : in Client_t; Failed : out Boolean); -- proc_map : jack_connect procedure Connect (Client : in Client_t; Source_Port : in Port_Name_t; Destination_Port : in Port_Name_t; Failed : out Boolean); -- proc_map : jack_disconnect procedure Disconnect (Client : in Client_t; Source_Port : in Port_Name_t; Destination_Port : in Port_Name_t; Failed : out Boolean); -- proc_map : jack_client_open procedure Open (Client_Name : in String; Options : in Options_t; Client : out Client_t; Status : in out Status_t); -- proc_map : jack_port_register procedure Port_Register (Client : in Client_t; Port : out Port_t; Port_Name : in Port_Name_t; Port_Type : in String; Port_Flags : in Port_Flags_t; Buffer_Size : in Natural := 0); -- proc_map : jack_activate procedure Activate (Client : in Client_t; Failed : out Boolean); -- proc_map : jack_get_ports procedure Get_Ports (Client : in Client_t; Port_Name_Pattern : in String; Port_Type_Pattern : in String; Port_Flags : in Port_Flags_t; Ports : out Port_Name_Set_t); generic type User_Data_Type is private; type User_Data_Access_Type is access User_Data_Type; package Generic_Callbacks is type Process_Callback_State_t is record Callback : access procedure (Number_Of_Frames : in Number_Of_Frames_t; User_Data : in User_Data_Access_Type); User_Data : User_Data_Access_Type; end record; type Process_Callback_State_Access_t is access Process_Callback_State_t; procedure Deallocate_State is new Ada.Unchecked_Deallocation (Object => User_Data_Type, Name => User_Data_Access_Type); -- proc_map : jack_set_process_callback procedure Set_Process_Callback (Client : in Client_t; State : in Process_Callback_State_Access_t; Failed : out Boolean); end Generic_Callbacks; -- -- Private -- function To_Address (Client : in Client_t) return System.Address; pragma Inline (To_Address); function To_Address (Port : in Port_t) return System.Address; pragma Inline (To_Address); private type Client_t is new System.Address; type Port_t is new System.Address; Invalid_Client : constant Client_t := Client_t (System.Null_Address); Invalid_Port : constant Port_t := Port_t (System.Null_Address); function Map_Status_To_Thin (Status : Status_t) return Thin.Status_t; pragma Inline (Map_Status_To_Thin); function Map_Thin_To_Status (Status : Thin.Status_t) return Status_t; pragma Inline (Map_Thin_To_Status); function Map_Options_To_Thin (Options : Options_t) return Thin.Options_t; pragma Inline (Map_Options_To_Thin); function Map_Thin_To_Options (Options : Thin.Options_t) return Options_t; pragma Inline (Map_Thin_To_Options); function Map_Port_Flags_To_Thin (Port_Flags : Port_Flags_t) return Thin.Port_Flags_t; pragma Inline (Map_Port_Flags_To_Thin); function Map_Thin_To_Port_Flags (Port_Flags : Thin.Port_Flags_t) return Port_Flags_t; pragma Inline (Map_Thin_To_Port_Flags); end Jack.Client;
Add Default_Audio_Type
Add Default_Audio_Type
Ada
isc
io7m/coreland-jack-ada,io7m/coreland-jack-ada
a0a8592adb9f0077795de6b76e77b46d2ddf7738
src/security-oauth-file_registry.adb
src/security-oauth-file_registry.adb
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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.Encoders.HMAC.SHA1; package body Security.OAuth.File_Registry is -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in File_Principal) return String is begin return To_String (From.Name); end Get_Name; -- ------------------------------ -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. -- ------------------------------ overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class is Pos : constant Application_Maps.Cursor := Realm.Applications.Find (Client_Id); begin if not Application_Maps.Has_Element (Pos) then raise Servers.Invalid_Application; end if; return Application_Maps.Element (Pos); end Find_Application; -- ------------------------------ -- Add the application to the application repository. -- ------------------------------ procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application) is begin Realm.Applications.Include (App.Get_Application_Identifier, App); end Add_Application; -- ------------------------------ -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. -- ------------------------------ overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token); begin if Token_Maps.Has_Element (Pos) then Auth := Token_Maps.Element (Pos).all'Access; else Auth := null; end if; Cacheable := True; end Authenticate; -- ------------------------------ -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. -- ------------------------------ overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String is begin return To_String (File_Principal (Auth.all).Token); end Authorize; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is Result : File_Principal_Access; Pos : constant User_Maps.Cursor := Realm.Users.Find (Username); begin if not User_Maps.Has_Element (Pos) then Auth := null; return; end if; -- Verify that the crypt password with the recorded salt are the same. declare Expect : constant String := User_Maps.Element (Pos); Hash : constant String := Realm.Crypt_Password (Expect, Password); begin if Hash /= Expect then Auth := null; return; end if; end; -- Generate a random token and make the principal to record it. declare Token : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Result := new File_Principal; Ada.Strings.Unbounded.Append (Result.Token, Token); Ada.Strings.Unbounded.Append (Result.Name, Username); Realm.Tokens.Insert (Token, Result); end; Auth := Result.all'Access; end Verify; overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access) is begin null; end Verify; overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access) is begin if Auth /= null and then Auth.all in File_Principal'Class then Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token)); end if; end Revoke; -- ------------------------------ -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. -- ------------------------------ function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String is pragma Unreferenced (Realm); Pos : Natural := Util.Strings.Index (Salt, ' '); begin if Pos = 0 then Pos := Salt'Last; else Pos := Pos - 1; end if; return Salt (Salt'First .. Pos) & " " & Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => Salt (Salt'First .. Pos), Data => Password, URL => True); end Crypt_Password; -- ------------------------------ -- Add a username with the associated password. -- ------------------------------ procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String) is Salt : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Realm.Users.Include (Username, Realm.Crypt_Password (Salt, Password)); end Add_User; end Security.OAuth.File_Registry;
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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.Encoders.HMAC.SHA1; with Util.Log.Loggers; package body Security.OAuth.File_Registry is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.File_Registry"); -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in File_Principal) return String is begin return To_String (From.Name); end Get_Name; -- ------------------------------ -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. -- ------------------------------ overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class is Pos : constant Application_Maps.Cursor := Realm.Applications.Find (Client_Id); begin if not Application_Maps.Has_Element (Pos) then raise Servers.Invalid_Application; end if; return Application_Maps.Element (Pos); end Find_Application; -- ------------------------------ -- Add the application to the application repository. -- ------------------------------ procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application) is begin Realm.Applications.Include (App.Get_Application_Identifier, App); end Add_Application; -- ------------------------------ -- Load from the properties the definition of applications. The list of applications -- is controled by the property <prefix>.list which contains a comma separated list of -- application names or ids. The application definition are represented by properties -- of the form: -- <prefix>.<app>.client_id -- <prefix>.<app>.client_secret -- <prefix>.<app>.callback_url -- ------------------------------ procedure Load (Realm : in out File_Application_Manager; Props : in Util.Properties.Manager'Class; Prefix : in String) is procedure Configure (Basename : in String); procedure Configure (Basename : in String) is App : Servers.Application; begin App.Set_Application_Identifier (Props.Get (Basename & ".client_id")); App.Set_Application_Secret (Props.Get (Basename & ".client_secret")); App.Set_Application_Callback (Props.Get (Basename & ".callback_url", "")); Realm.Add_Application (App); end Configure; List : constant String := Props.Get (Prefix & ".list"); First : Natural := List'First; Last : Natural; Count : Natural := 0; begin Log.Info ("Loading application with prefix {0}", Prefix); while First <= List'Last loop Last := Util.Strings.Index (Source => List, Char => ',', From => First); if Last = 0 then Last := List'Last; else Last := Last - 1; end if; begin Configure (Prefix & "." & List (First .. Last)); Count := Count + 1; exception when others => Log.Error ("Invalid application definition {0}", Prefix & "." & List (First .. Last)); end; First := Last + 2; end loop; Log.Info ("Loaded {0} applications", Util.Strings.Image (Count)); end Load; procedure Load (Realm : in out File_Application_Manager; Path : in String; Prefix : in String) is Props : Util.Properties.Manager; begin Log.Info ("Loading application with prefix {0} from {1}", Prefix, Path); Props.Load_Properties (Path); Realm.Load (Props, Prefix); end Load; -- ------------------------------ -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. -- ------------------------------ overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token); begin if Token_Maps.Has_Element (Pos) then Auth := Token_Maps.Element (Pos).all'Access; else Auth := null; end if; Cacheable := True; end Authenticate; -- ------------------------------ -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. -- ------------------------------ overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String is begin return To_String (File_Principal (Auth.all).Token); end Authorize; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is Result : File_Principal_Access; Pos : constant User_Maps.Cursor := Realm.Users.Find (Username); begin if not User_Maps.Has_Element (Pos) then Auth := null; return; end if; -- Verify that the crypt password with the recorded salt are the same. declare Expect : constant String := User_Maps.Element (Pos); Hash : constant String := Realm.Crypt_Password (Expect, Password); begin if Hash /= Expect then Auth := null; return; end if; end; -- Generate a random token and make the principal to record it. declare Token : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Result := new File_Principal; Ada.Strings.Unbounded.Append (Result.Token, Token); Ada.Strings.Unbounded.Append (Result.Name, Username); Realm.Tokens.Insert (Token, Result); end; Auth := Result.all'Access; end Verify; overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access) is begin null; end Verify; overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access) is begin if Auth /= null and then Auth.all in File_Principal'Class then Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token)); end if; end Revoke; -- ------------------------------ -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. -- ------------------------------ function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String is pragma Unreferenced (Realm); Pos : Natural := Util.Strings.Index (Salt, ' '); begin if Pos = 0 then Pos := Salt'Last; else Pos := Pos - 1; end if; return Salt (Salt'First .. Pos) & " " & Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => Salt (Salt'First .. Pos), Data => Password, URL => True); end Crypt_Password; -- ------------------------------ -- Add a username with the associated password. -- ------------------------------ procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String) is Salt : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Realm.Users.Include (Username, Realm.Crypt_Password (Salt, Password)); end Add_User; end Security.OAuth.File_Registry;
Implement the Load procedure to load application definitions from a property file
Implement the Load procedure to load application definitions from a property file
Ada
apache-2.0
stcarrez/ada-security
18fb881fbff2c5dee26500aa6f9796195696732d
awa/awaunit/awa-tests.adb
awa/awaunit/awa-tests.adb
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- 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_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with ASF.Server.Web; with ASF.Converters.Dates; with ASF.Tests; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; -- with AWA.Applications; with AWA.Applications.Factory; with AWA.Services.Filters; with AWA.Services.Contexts; package body AWA.Tests is protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new AWA.Applications.Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); if Add_Modules then declare Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Tests.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; end AWA.Tests;
----------------------------------------------------------------------- -- AWA tests - AWA Tests Framework -- 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_Termination; with Ada.Task_Identification; with Ada.Exceptions; with Ada.Unchecked_Deallocation; with ASF.Server.Tests; with ASF.Server.Web; with ASF.Converters.Dates; with ASF.Tests; with AWA.Converters.Dates; with AWA.Users.Modules; with AWA.Mail.Modules; with AWA.Blogs.Modules; with AWA.Workspaces.Modules; with AWA.Storages.Modules; -- with AWA.Applications; with AWA.Applications.Factory; with AWA.Services.Filters; with AWA.Services.Contexts; package body AWA.Tests is protected Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence); end Shutdown; Application_Created : Boolean := False; Application : AWA.Applications.Application_Access := null; Factory : AWA.Applications.Factory.Application_Factory; Service_Filter : aliased AWA.Services.Filters.Service_Filter; Users : aliased AWA.Users.Modules.User_Module; Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module; Mail : aliased AWA.Mail.Modules.Mail_Module; Blogs : aliased AWA.Blogs.Modules.Blog_Module; Storages : aliased AWA.Storages.Modules.Storage_Module; Date_Converter : aliased ASF.Converters.Dates.Date_Converter; Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter; protected body Shutdown is procedure Termination (Cause : in Ada.Task_Termination.Cause_Of_Termination; Id : in Ada.Task_Identification.Task_Id; Ex : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (Cause, Id, Ex); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin Free (Application); end Termination; end Shutdown; -- ------------------------------ -- Setup the service context before executing the test. -- ------------------------------ overriding procedure Set_Up (T : in out Test) is pragma Unreferenced (T); begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Up; procedure Initialize (Props : in Util.Properties.Manager) is begin Initialize (null, Props, True); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => AWA.Applications.Application'Class, Name => AWA.Applications.Application_Access); begin if Application_Created then Free (Application); end if; end Finish; -- ------------------------------ -- Initialize the AWA test framework mockup. -- ------------------------------ procedure Initialize (App : in AWA.Applications.Application_Access; Props : in Util.Properties.Manager; Add_Modules : in Boolean) is use AWA.Applications; begin -- Create the application unless it is specified as argument. -- Install a shutdown hook to delete the application when the primary task exits. -- This allows to stop the event threads if any. if App = null then Application_Created := True; Application := new AWA.Applications.Application; Ada.Task_Termination.Set_Specific_Handler (Ada.Task_Identification.Current_Task, Shutdown.Termination'Access); else Application := App; end if; ASF.Tests.Initialize (Props, Application.all'Access, Factory); Application.Add_Filter ("service", Service_Filter'Access); Application.Add_Filter_Mapping (Name => "service", Pattern => "*.html"); if Add_Modules then declare Ctx : AWA.Services.Contexts.Service_Context; Users : constant AWA.Users.Modules.User_Module_Access := AWA.Tests.Users'Access; begin Ctx.Set_Context (Application, null); Register (App => Application.all'Access, Name => AWA.Users.Modules.NAME, URI => "user", Module => Users.all'Access); Register (App => Application.all'Access, Name => "mail", URI => "mail", Module => Mail'Access); Register (App => Application.all'Access, Name => "workspaces", URI => "workspaces", Module => Workspaces'Access); Register (App => Application.all'Access, Name => AWA.Storages.Modules.NAME, URI => "storages", Module => Storages'Access); Register (App => Application.all'Access, Name => AWA.Blogs.Modules.NAME, URI => "blogs", Module => Blogs'Access); if Props.Exists ("test.server") then declare WS : ASF.Server.Web.AWS_Container; begin Application.Add_Converter (Name => "dateConverter", Converter => Date_Converter'Access); Application.Add_Converter (Name => "smartDateConverter", Converter => Rel_Date_Converter'Access); WS.Register_Application ("/asfunit", Application.all'Access); WS.Start; delay 6000.0; end; end if; ASF.Server.Tests.Set_Context (Application.all'Access); end; end if; end Initialize; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return AWA.Applications.Application_Access is begin return Application; end Get_Application; -- ------------------------------ -- Set the application context to simulate a web request context. -- ------------------------------ procedure Set_Application_Context is begin ASF.Server.Tests.Set_Context (Application.all'Access); end Set_Application_Context; end AWA.Tests;
Add a relative date converter
Add a relative date converter
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
26e68a922285d96b523d6d265e3b32b7f7e1a99d
src/wiki-parsers-markdown.ads
src/wiki-parsers-markdown.ads
----------------------------------------------------------------------- -- wiki-parsers-markdown -- Markdown parser operations -- Copyright (C) 2016 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private package Wiki.Parsers.Markdown is pragma Preelaborate; subtype Parser_Type is Parser; -- Parse a markdown table/column. -- Example: -- | col1 | col2 | ... | colN | procedure Parse_Table (P : in out Parser; Token : in Wiki.Strings.WChar); procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access); procedure Parse_Inline_Text (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access); end Wiki.Parsers.Markdown;
----------------------------------------------------------------------- -- wiki-parsers-markdown -- Markdown parser operations -- Copyright (C) 2016 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private package Wiki.Parsers.Markdown is pragma Preelaborate; subtype Parser_Type is Parser; procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access); procedure Parse_Inline_Text (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access); end Wiki.Parsers.Markdown;
Remove declaration of internal Parse_Table procedure
Remove declaration of internal Parse_Table procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
46f6b471050133442f3bfe09973cf222f1ba37be
src/babel-strategies-default.adb
src/babel-strategies-default.adb
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files.Signatures; with Util.Encoders.SHA1; with Util.Log.Loggers; package body Babel.Strategies.Default is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies.Default"); -- Returns true if there is a directory that must be processed by the current strategy. overriding function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is begin return false; -- not Strategy.Queue.Directories.Is_Empty; end Has_Directory; -- Get the next directory that must be processed by the strategy. overriding procedure Peek_Directory (Strategy : in out Default_Strategy_Type; Directory : out Babel.Files.Directory_Type) is Last : constant String := ""; -- Strategy.Queue.Directories.Last_Element; begin -- Strategy.Queue.Directories.Delete_Last; null; end Peek_Directory; -- Set the file queue that the strategy must use. procedure Set_Queue (Strategy : in out Default_Strategy_Type; Queue : in Babel.Files.Queues.File_Queue_Access) is begin Strategy.Queue := Queue; end Set_Queue; overriding procedure Execute (Strategy : in out Default_Strategy_Type) is use type Babel.Files.File_Type; Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer; File : Babel.Files.File_Type; SHA1 : Util.Encoders.SHA1.Hash_Array; begin Strategy.Queue.Queue.Dequeue (File, 10.0); if File = Babel.Files.NO_FILE then Log.Debug ("Dequeue NO_FILE"); Strategy.Release_Buffer (Content); else Log.Debug ("Dequeue {0}", Babel.Files.Get_Path (File)); Strategy.Read_File (File, Content); Babel.Files.Signatures.Sha1 (Content.all, SHA1); Babel.Files.Set_Signature (File, SHA1); if Babel.Files.Is_Modified (File) then Strategy.Backup_File (File, Content); else Strategy.Release_Buffer (Content); end if; end if; exception when others => Strategy.Release_Buffer (Content); raise; end Execute; -- Scan the directory overriding procedure Scan (Strategy : in out Default_Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is procedure Add_Queue (File : in Babel.Files.File_Type) is begin Log.Debug ("Queueing {0}", Babel.Files.Get_Path (File)); Strategy.Queue.Add_File (File); end Add_Queue; begin Strategy_Type (Strategy).Scan (Directory, Container); Container.Each_File (Add_Queue'Access); end Scan; -- overriding -- procedure Add_File (Into : in out Default_Strategy_Type; -- Path : in String; -- Element : in Babel.Files.File) is -- begin -- Into.Queue.Add_File (Path, Element); -- end Add_File; -- -- overriding -- procedure Add_Directory (Into : in out Default_Strategy_Type; -- Path : in String; -- Name : in String) is -- begin -- Into.Queue.Add_Directory (Path, Name); -- end Add_Directory; end Babel.Strategies.Default;
----------------------------------------------------------------------- -- babel-strategies -- Strategies to backup files -- Copyright (C) 2014, 2015, 2016 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- pragma Ada_2012; with Babel.Files.Signatures; with Util.Encoders.SHA1; with Util.Log.Loggers; with Babel.Streams.Refs; package body Babel.Strategies.Default is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Strategies.Default"); -- Returns true if there is a directory that must be processed by the current strategy. overriding function Has_Directory (Strategy : in Default_Strategy_Type) return Boolean is begin return false; -- not Strategy.Queue.Directories.Is_Empty; end Has_Directory; -- Get the next directory that must be processed by the strategy. overriding procedure Peek_Directory (Strategy : in out Default_Strategy_Type; Directory : out Babel.Files.Directory_Type) is Last : constant String := ""; -- Strategy.Queue.Directories.Last_Element; begin -- Strategy.Queue.Directories.Delete_Last; null; end Peek_Directory; -- Set the file queue that the strategy must use. procedure Set_Queue (Strategy : in out Default_Strategy_Type; Queue : in Babel.Files.Queues.File_Queue_Access) is begin Strategy.Queue := Queue; end Set_Queue; overriding procedure Execute (Strategy : in out Default_Strategy_Type) is use type Babel.Files.File_Type; Content : Babel.Files.Buffers.Buffer_Access := Strategy.Allocate_Buffer; File : Babel.Files.File_Type; SHA1 : Util.Encoders.SHA1.Hash_Array; Stream : Babel.Streams.Refs.Stream_Ref; begin Strategy.Queue.Queue.Dequeue (File, 10.0); if File = Babel.Files.NO_FILE then Log.Debug ("Dequeue NO_FILE"); Strategy.Release_Buffer (Content); else Log.Debug ("Dequeue {0}", Babel.Files.Get_Path (File)); Strategy.Read_File (File, Stream); Babel.Files.Signatures.Sha1 (Stream, SHA1); Babel.Files.Set_Signature (File, SHA1); if Babel.Files.Is_Modified (File) then Strategy.Backup_File (File, Stream); else Strategy.Release_Buffer (Content); end if; end if; exception when others => Strategy.Release_Buffer (Content); raise; end Execute; -- Scan the directory overriding procedure Scan (Strategy : in out Default_Strategy_Type; Directory : in Babel.Files.Directory_Type; Container : in out Babel.Files.File_Container'Class) is procedure Add_Queue (File : in Babel.Files.File_Type) is begin Log.Debug ("Queueing {0}", Babel.Files.Get_Path (File)); Strategy.Queue.Add_File (File); end Add_Queue; begin Strategy_Type (Strategy).Scan (Directory, Container); Container.Each_File (Add_Queue'Access); end Scan; -- overriding -- procedure Add_File (Into : in out Default_Strategy_Type; -- Path : in String; -- Element : in Babel.Files.File) is -- begin -- Into.Queue.Add_File (Path, Element); -- end Add_File; -- -- overriding -- procedure Add_Directory (Into : in out Default_Strategy_Type; -- Path : in String; -- Name : in String) is -- begin -- Into.Queue.Add_Directory (Path, Name); -- end Add_Directory; end Babel.Strategies.Default;
Use the Read_File and Write_File operation on a stream for the backup
Use the Read_File and Write_File operation on a stream for the backup
Ada
apache-2.0
stcarrez/babel
dfa878c74f4740cae5c7c4865d7e9f4c7e42b1cb
mat/src/mat-readers-marshaller.adb
mat/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : constant Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : constant MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with System; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : constant Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; -- ------------------------------ -- Get an 8-bit value from the buffer. -- ------------------------------ function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; -- ------------------------------ -- Get a 16-bit value either from big-endian or little endian. -- ------------------------------ function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer; Low : Object_Pointer; begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := To_Pointer (Buffer.Current); High := To_Pointer (Buffer.Current + Storage_Offset (1)); else High := To_Pointer (Buffer.Current); Low := To_Pointer (Buffer.Current + Storage_Offset (1)); end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; Low, High : MAT.Types.Uint16; begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; if Buffer.Endian = LITTLE_ENDIAN then Low := Get_Uint16 (Buffer); High := Get_Uint16 (Buffer); else High := Get_Uint16 (Buffer); Low := Get_Uint16 (Buffer); end if; return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low); end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : constant MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is begin return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg)); end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
Document Get_Uint16
Document Get_Uint16
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
9f9595d4c7d222e025623c6700394bdb5c4a2ac9
mat/src/mat-readers-marshaller.adb
mat/src/mat-readers-marshaller.adb
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with MAT.Types; with Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : Object_Pointer := To_Pointer (Buffer.Current + Storage_Offset (1)); Low : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; P : Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 4; Buffer.Current := Buffer.Current + Storage_Offset (4); if Buffer.Current >= Buffer.Last then Buffer.Current := Buffer.Start; end if; return P.all; end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.EVents.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- Ipc -- Ipc channel between profiler tool and application -- -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; use System; with System.Address_To_Access_Conversions; with System.Storage_Elements; with Util.Log.Loggers; with Interfaces; use Interfaces; package body MAT.Readers.Marshaller is use System.Storage_Elements; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller"); package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8); package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32); function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is use Uint32_Access; P : constant Object_Pointer := To_Pointer (Buf); begin return P.all; end Get_Raw_Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is use Uint8_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size = 0 then Log.Error ("Not enough data to get a uint8"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 1; Buffer.Current := Buffer.Current + Storage_Offset (1); return P.all; end Get_Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is use Uint8_Access; High : constant Object_Pointer := To_Pointer (Buffer.Current + Storage_Offset (1)); Low : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size <= 1 then Log.Error ("Not enough data to get a uint16"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 2; Buffer.Current := Buffer.Current + Storage_Offset (2); return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all); end Get_Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is use Uint32_Access; P : constant Object_Pointer := To_Pointer (Buffer.Current); begin if Buffer.Size < 4 then Log.Error ("Not enough data to get a uint32"); raise Buffer_Underflow_Error; end if; Buffer.Size := Buffer.Size - 4; Buffer.Current := Buffer.Current + Storage_Offset (4); if Buffer.Current >= Buffer.Last then Buffer.Current := Buffer.Start; end if; return P.all; end Get_Uint32; function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is Val : constant MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer)); begin return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32; end Get_Uint64; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type is begin case Kind is when MAT.Events.T_UINT8 => return Target_Type (Get_Uint8 (Msg)); when MAT.Events.T_UINT16 => return Target_Type (Get_Uint16 (Msg)); when MAT.Events.T_UINT32 => return Target_Type (Get_Uint32 (Msg)); when MAT.Events.T_UINT64 => return Target_Type (Get_Uint64 (Msg)); when others => Log.Error ("Invalid attribute type {0}", MAT.Events.Attribute_Type'Image (Kind)); return 0; end case; end Get_Target_Value; -- ------------------------------ -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. -- ------------------------------ function Get_String (Buffer : in Buffer_Ptr) return String is Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer); Result : String (1 .. Natural (Len)); begin for I in Result'Range loop Result (I) := Character'Val (Get_Uint8 (Buffer)); end loop; return Result; end Get_String; -- ------------------------------ -- Skip the given number of bytes from the message. -- ------------------------------ procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural) is begin Buffer.Size := Buffer.Size - Size; Buffer.Current := Buffer.Current + Storage_Offset (Size); end Skip; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is function Get_Value is new Get_Target_Value (MAT.Types.Target_Size); begin return Get_Value (Msg, Kind); end Get_Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr); begin return Get_Value (Msg, Kind); end Get_Target_Uint32; end MAT.Readers.Marshaller;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
84b63372f2af058e5a48ebb4131a61320ae0d390
src/imago.ads
src/imago.ads
------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: ISC -- -- -- -- Copyright © 2015 darkestkhan -- ------------------------------------------------------------------------------ -- Permission to use, copy, modify, and/or 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 Imago is -------------------------------------------------------------------------- pragma Pure; -------------------------------------------------------------------------- end Imago;
------------------------------------------------------------------------------ -- EMAIL: <[email protected]> -- -- License: ISC -- -- -- -- Copyright © 2015 darkestkhan -- ------------------------------------------------------------------------------ -- Permission to use, copy, modify, and/or 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 Imago is -------------------------------------------------------------------------- pragma Pure; -------------------------------------------------------------------------- private --------------------------------------------------------------------------- pragma Linker_Options ("-IL -ILU -ILUT"); --------------------------------------------------------------------------- end Imago;
Add pragma Linker_Options.
Add pragma Linker_Options. Users of this library no longer need to remember to pass linker options into linker. Signed-off-by: darkestkhan <[email protected]>
Ada
isc
darkestkhan/imago
6822a79ff9a1f60e26ff29f6ace800f6e585352b
src/gen-model-beans.ads
src/gen-model-beans.ads
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Bean Definition -- ------------------------------ type Bean_Definition is new Tables.Table_Definition with null record; type Bean_Definition_Access is access all Bean_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 : in Bean_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Bean_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Bean_Definition); -- Create an attribute with the given name and add it to the bean. procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access); -- Create a bean with the given name. function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access; end Gen.Model.Beans;
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.Tables; with Gen.Model.Operations; package Gen.Model.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Bean Definition -- ------------------------------ type Bean_Definition is new Tables.Table_Definition with null record; type Bean_Definition_Access is access all Bean_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 : in Bean_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Bean_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Bean_Definition); -- Create an attribute with the given name and add it to the bean. procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access); -- Create a bean with the given name. function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access; end Gen.Model.Beans;
Use the operations model
Use the operations model
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
9f8a3cc6e1bae2c995fe146a3872c5e933c0ce35
src/util-commands-drivers.ads
src/util-commands-drivers.ads
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Commands.Parsers; private with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Ordered_Maps; -- == Command line driver == -- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line -- tools that have different commands identified by a name. generic -- The command execution context. type Context_Type (<>) is limited private; with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>); Driver_Name : String := "Drivers"; package Util.Commands.Drivers is subtype Config_Type is Config_Parser.Config_Type; -- A simple command handler executed when the command with the given name is executed. type Command_Handler is not null access procedure (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- A more complex command handler that has a command instance as context. type Command_Type is abstract tagged limited private; type Command_Access is access all Command_Type'Class; -- Execute the command with the arguments. The command name is passed with the command -- arguments. procedure Execute (Command : in Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Command_Type; Config : in out Config_Type) is null; -- Write the help associated with the command. procedure Help (Command : in Command_Type; Context : in out Context_Type) is abstract; -- Write the command usage. procedure Usage (Command : in Command_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); type Help_Command_Type is new Command_Type with private; -- Execute the help command with the arguments. -- Print the help for every registered command. overriding procedure Execute (Command : in Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. procedure Help (Command : in Help_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited private; -- Report the command usage. procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class); -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : in String); -- Set the driver usage printed in the usage. procedure Set_Usage (Driver : in out Driver_Type; Usage : in String); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler); -- Find the command having the given name. -- Returns null if the command was not found. function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access; -- Execute the command registered under the given name. procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); private package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Command_Access, "<" => "<"); type Command_Type is abstract tagged limited record Driver : access Driver_Type'Class; end record; type Help_Command_Type is new Command_Type with null record; type Handler_Command_Type is new Command_Type with record Handler : Command_Handler; end record; -- Execute the command with the arguments. overriding procedure Execute (Command : in Handler_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 Handler_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited record List : Command_Maps.Map; Desc : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands.Drivers;
----------------------------------------------------------------------- -- util-commands-drivers -- Support to make command line tools -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Commands.Parsers; private with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Ordered_Maps; -- == Command line driver == -- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line -- tools that have different commands identified by a name. generic -- The command execution context. type Context_Type (<>) is limited private; with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>); Driver_Name : String := "Drivers"; package Util.Commands.Drivers is subtype Config_Type is Config_Parser.Config_Type; -- A simple command handler executed when the command with the given name is executed. type Command_Handler is not null access procedure (Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- A more complex command handler that has a command instance as context. type Command_Type is abstract tagged limited private; type Command_Access is access all Command_Type'Class; -- Execute the command with the arguments. The command name is passed with the command -- arguments. procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is abstract; -- Setup the command before parsing the arguments and executing it. procedure Setup (Command : in out Command_Type; Config : in out Config_Type) is null; -- Write the help associated with the command. procedure Help (Command : in Command_Type; Context : in out Context_Type) is abstract; -- Write the command usage. procedure Usage (Command : in out Command_Type; Name : in String); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. -- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure. procedure Log (Command : in Command_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); type Help_Command_Type is new Command_Type with private; -- Execute the help command with the arguments. -- Print the help for every registered command. overriding procedure Execute (Command : in out Help_Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Write the help associated with the command. procedure Help (Command : in Help_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited private; -- Report the command usage. procedure Usage (Driver : in Driver_Type; Args : in Argument_List'Class; Name : in String := ""); -- Set the driver description printed in the usage. procedure Set_Description (Driver : in out Driver_Type; Description : in String); -- Set the driver usage printed in the usage. procedure Set_Usage (Driver : in out Driver_Type; Usage : in String); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Command : in Command_Access); -- Register the command under the given name. procedure Add_Command (Driver : in out Driver_Type; Name : in String; Handler : in Command_Handler); -- Find the command having the given name. -- Returns null if the command was not found. function Find_Command (Driver : in Driver_Type; Name : in String) return Command_Access; -- Execute the command registered under the given name. procedure Execute (Driver : in Driver_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Print a message for the command. The level indicates whether the message is an error, -- warning or informational. The command name can be used to known the originator. procedure Log (Driver : in Driver_Type; Level : in Util.Log.Level_Type; Name : in String; Message : in String); private package Command_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String, Element_Type => Command_Access, "<" => "<"); type Command_Type is abstract tagged limited record Driver : access Driver_Type'Class; end record; type Help_Command_Type is new Command_Type with null record; type Handler_Command_Type is new Command_Type with record Handler : Command_Handler; end record; -- Execute the command with the arguments. overriding procedure Execute (Command : in out Handler_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 Handler_Command_Type; Context : in out Context_Type); type Driver_Type is tagged limited record List : Command_Maps.Map; Desc : Ada.Strings.Unbounded.Unbounded_String; Usage : Ada.Strings.Unbounded.Unbounded_String; end record; end Util.Commands.Drivers;
Change the Execute procedure to accept in out parameter for ther Comment_Type Add Name parameter to the Usage procedure
Change the Execute procedure to accept in out parameter for ther Comment_Type Add Name parameter to the Usage procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
f5ca49f9b25db238c439e8fad7bbbdeba4309d30
awa/src/awa-commands-start.ads
awa/src/awa-commands-start.ads
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- 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 GNAT.Command_Line; with GNAT.Strings; with AWA.Commands.Drivers; generic with package Command_Drivers is new AWA.Commands.Drivers (<>); package AWA.Commands.Start is type Command_Type is new Command_Drivers.Command_Type with record Management_Port : aliased Integer := 0; Listening_Port : aliased Integer := 8080; Upload_Size_Limit : aliased Integer := 16#500_000#; Max_Connection : aliased Integer := 5; TCP_No_Delay : aliased Boolean := False; Daemon : aliased Boolean := False; Upload : aliased GNAT.Strings.String_Access; end record; -- Start the server and all the application that have been registered. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type); Command : aliased Command_Type; end AWA.Commands.Start;
----------------------------------------------------------------------- -- awa-commands-start -- Command to start the web server -- 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 GNAT.Command_Line; with GNAT.Strings; with AWA.Commands.Drivers; generic with package Command_Drivers is new AWA.Commands.Drivers (<>); package AWA.Commands.Start is type Command_Type is new Command_Drivers.Command_Type with record Management_Port : aliased Integer := 0; Listening_Port : aliased Integer := 8080; Upload_Size_Limit : aliased Integer := 16#500_000#; Max_Connection : aliased Integer := 5; TCP_No_Delay : aliased Boolean := False; Daemon : aliased Boolean := False; Upload : aliased GNAT.Strings.String_Access; end record; -- Start the server and all the application that have been registered. overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type); -- Start the server and all the application that have been registered. procedure Start_Server (Command : in out Command_Type; Context : in out Context_Type); -- Wait for the server to shutdown. procedure Wait_Server (Command : in out Command_Type; Context : in out Context_Type); -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type); -- Write the help associated with the command. overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type); Command : aliased Command_Type; end AWA.Commands.Start;
Add Start_Server and Wait_Server operations
Add Start_Server and Wait_Server operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2f2af21d90054ea73cc8fed049ef37f48c3d2e8e
mat/src/mat-expressions.adb
mat/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Memory; package body MAT.Expressions is -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Context : in Context_Type) return Boolean is use type MAT.Types.Target_Size; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Context); when N_AND => return Is_Selected (Node.Left.all, Context) and then Is_Selected (Node.Right.all, Context); when N_OR => return Is_Selected (Node.Left.all, Context) or else Is_Selected (Node.Right.all, Context); when N_RANGE_SIZE => return Context.Allocation.Size >= Node.Min_Size and Context.Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Context.Addr >= Node.Min_Addr and Context.Addr <= Node.Max_Addr; when others => return False; end case; end Is_Selected; end MAT.Expressions;
Implement the Is_Selected operation on some node types
Implement the Is_Selected operation on some node types
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
1a3699783fd97fba0adf4aeb0f36758ca90db561
src/http/util-http-clients.adb
src/http/util-http-clients.adb
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Http.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients"); -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Request : in Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; if Http.Manager = null then Log.Error ("No HTTP manager was defined"); raise Program_Error with "No HTTP manager was defined."; end if; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; -- ------------------------------ -- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Put (Request, URL, Data, Reply); end Put; -- ------------------------------ -- Execute a http DELETE request on the given URL. -- ------------------------------ procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Delete (Request, URL, Reply); end Delete; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ procedure Set_Timeout (Request : in out Client; Timeout : in Duration) is begin Request.Manager.Set_Timeout (Request, Timeout); end Set_Timeout; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
----------------------------------------------------------------------- -- util-http-clients -- HTTP Clients -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Http.Clients is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients"); procedure Initialize (Form : in out Form_Data; Size : in Positive) is begin Form.Buffer.Initialize (Output => null, Size => Size); Form.Initialize (Form.Buffer'Unchecked_Access); end Initialize; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Reply : in Response; Name : in String) return Boolean is begin if Reply.Delegate = null then return False; else return Reply.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified response header as a String. If the response -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Reply : in Response; Name : in String) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a message header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a request header with the given name and value. -- This method allows request headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Reply : in out Response; Name : in String; Value : in String) is begin Reply.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the response headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Reply : in Response; Process : not null access procedure (Name : in String; Value : in String)) is begin if Reply.Delegate /= null then Reply.Delegate.Iterate_Headers (Process); end if; end Iterate_Headers; -- ------------------------------ -- Get the response body as a string. -- ------------------------------ overriding function Get_Body (Reply : in Response) return String is begin if Reply.Delegate = null then return ""; else return Reply.Delegate.Get_Body; end if; end Get_Body; -- ------------------------------ -- Get the response status code. -- ------------------------------ function Get_Status (Reply : in Response) return Natural is begin return Reply.Delegate.Get_Status; end Get_Status; -- ------------------------------ -- Returns a boolean indicating whether the named response header has already -- been set. -- ------------------------------ overriding function Contains_Header (Request : in Client; Name : in String) return Boolean is begin if Request.Delegate = null then return False; else return Request.Delegate.Contains_Header (Name); end if; end Contains_Header; -- ------------------------------ -- Returns the value of the specified request header as a String. If the request -- did not include a header of the specified name, this method returns null. -- If there are multiple headers with the same name, this method returns the -- first head in the request. The header name is case insensitive. You can use -- this method with any response header. -- ------------------------------ overriding function Get_Header (Request : in Client; Name : in String) return String is begin if Request.Delegate = null then return ""; else return Request.Delegate.Get_Header (Name); end if; end Get_Header; -- ------------------------------ -- Sets a header with the given name and value. If the header had already -- been set, the new value overwrites the previous one. The containsHeader -- method can be used to test for the presence of a header before setting its value. -- ------------------------------ overriding procedure Set_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Set_Header (Name, Value); end Set_Header; -- ------------------------------ -- Adds a header with the given name and value. -- This method allows headers to have multiple values. -- ------------------------------ overriding procedure Add_Header (Request : in out Client; Name : in String; Value : in String) is begin Request.Delegate.Add_Header (Name, Value); end Add_Header; -- ------------------------------ -- Iterate over the request headers and executes the <b>Process</b> procedure. -- ------------------------------ overriding procedure Iterate_Headers (Request : in Client; Process : not null access procedure (Name : in String; Value : in String)) is begin Request.Delegate.Iterate_Headers (Process); end Iterate_Headers; -- ------------------------------ -- Removes all headers with the given name. -- ------------------------------ procedure Remove_Header (Request : in out Client; Name : in String) is begin null; end Remove_Header; -- ------------------------------ -- Initialize the client -- ------------------------------ overriding procedure Initialize (Http : in out Client) is begin Http.Delegate := null; Http.Manager := Default_Http_Manager; if Http.Manager = null then Log.Error ("No HTTP manager was defined"); raise Program_Error with "No HTTP manager was defined."; end if; Http.Manager.Create (Http); end Initialize; overriding procedure Finalize (Http : in out Client) is procedure Free is new Ada.Unchecked_Deallocation (Http_Request'Class, Http_Request_Access); begin Free (Http.Delegate); end Finalize; -- ------------------------------ -- Execute an http GET request on the given URL. Additional request parameters, -- cookies and headers should have been set on the client object. -- ------------------------------ procedure Get (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Get (Request, URL, Reply); end Get; -- ------------------------------ -- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Post (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Data, Reply); end Post; procedure Post (Request : in out Client; URL : in String; Data : in Form_Data'Class; Reply : out Response'Class) is begin Request.Manager.Do_Post (Request, URL, Util.Streams.Texts.To_String (Data.Buffer), Reply); end Post; -- ------------------------------ -- Execute an http PUT request on the given URL. The post data is passed in <b>Data</b>. -- Additional request cookies and headers should have been set on the client object. -- ------------------------------ procedure Put (Request : in out Client; URL : in String; Data : in String; Reply : out Response'Class) is begin Request.Manager.Do_Put (Request, URL, Data, Reply); end Put; -- ------------------------------ -- Execute a http DELETE request on the given URL. -- ------------------------------ procedure Delete (Request : in out Client; URL : in String; Reply : out Response'Class) is begin Request.Manager.Do_Delete (Request, URL, Reply); end Delete; -- ------------------------------ -- Set the timeout for the connection. -- ------------------------------ procedure Set_Timeout (Request : in out Client; Timeout : in Duration) is begin Request.Manager.Set_Timeout (Request, Timeout); end Set_Timeout; -- ------------------------------ -- Adds the specified cookie to the request. This method can be called multiple -- times to set more than one cookie. -- ------------------------------ procedure Add_Cookie (Http : in out Client; Cookie : in Util.Http.Cookies.Cookie) is begin null; end Add_Cookie; -- ------------------------------ -- Free the resource used by the response. -- ------------------------------ overriding procedure Finalize (Reply : in out Response) is procedure Free is new Ada.Unchecked_Deallocation (Http_Response'Class, Http_Response_Access); begin Free (Reply.Delegate); end Finalize; end Util.Http.Clients;
Implement the Initialize procedure to setup the Form_Data buffer Implement the Post procedure to get a Form_Data as parameter
Implement the Initialize procedure to setup the Form_Data buffer Implement the Post procedure to get a Form_Data as parameter
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c0170264d5e033b4c7b06d7452eccbbac9fb2612
awa/plugins/awa-comments/src/model/awa-comments-models.ads
awa/plugins/awa-comments/src/model/awa-comments-models.ads
----------------------------------------------------------------------- -- AWA.Comments.Models -- AWA.Comments.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off, "unit * is not referenced"); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Objects.Enums; with Util.Beans.Basic.Lists; with AWA.Users.Models; with Util.Beans.Methods; pragma Warnings (On, "unit * is not referenced"); package AWA.Comments.Models is -- -------------------- -- The status type defines whether the comment is visible or not. -- The comment can be put in the COMMENT_WAITING state so that -- it is not immediately visible. It must be put in the COMMENT_PUBLISHED -- state to be visible. -- -------------------- type Status_Type is (COMMENT_PUBLISHED, COMMENT_WAITING, COMMENT_SPAM, COMMENT_BLOCKED, COMMENT_ARCHIVED); for Status_Type use (COMMENT_PUBLISHED => 0, COMMENT_WAITING => 1, COMMENT_SPAM => 2, COMMENT_BLOCKED => 3, COMMENT_ARCHIVED => 4); package Status_Type_Objects is new Util.Beans.Objects.Enums (Status_Type); type Comment_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The Comment table records a user comment associated with a database entity. -- The comment can be associated with any other database record. -- -------------------- -- Create an object key for Comment. function Comment_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Comment from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Comment_Key (Id : in String) return ADO.Objects.Object_Key; Null_Comment : constant Comment_Ref; function "=" (Left, Right : Comment_Ref'Class) return Boolean; -- Set the comment publication date procedure Set_Create_Date (Object : in out Comment_Ref; Value : in Ada.Calendar.Time); -- Get the comment publication date function Get_Create_Date (Object : in Comment_Ref) return Ada.Calendar.Time; -- Set the comment message. procedure Set_Message (Object : in out Comment_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Message (Object : in out Comment_Ref; Value : in String); -- Get the comment message. function Get_Message (Object : in Comment_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Message (Object : in Comment_Ref) return String; -- Set the entity identifier to which this comment is associated procedure Set_Entity_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the entity identifier to which this comment is associated function Get_Entity_Id (Object : in Comment_Ref) return ADO.Identifier; -- Set the comment identifier procedure Set_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the comment identifier function Get_Id (Object : in Comment_Ref) return ADO.Identifier; -- Get the optimistic lock version. function Get_Version (Object : in Comment_Ref) return Integer; -- Set the entity type that identifies the table to which the comment is associated. procedure Set_Entity_Type (Object : in out Comment_Ref; Value : in ADO.Entity_Type); -- Get the entity type that identifies the table to which the comment is associated. function Get_Entity_Type (Object : in Comment_Ref) return ADO.Entity_Type; -- Set the comment status to decide whether the comment is visible (published) or not. procedure Set_Status (Object : in out Comment_Ref; Value : in Status_Type); -- Get the comment status to decide whether the comment is visible (published) or not. function Get_Status (Object : in Comment_Ref) return Status_Type; -- procedure Set_Author (Object : in out Comment_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Author (Object : in Comment_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Comment_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Comment_Ref); -- Copy of the object. procedure Copy (Object : in Comment_Ref; Into : in out Comment_Ref); -- -------------------- -- The comment information. -- -------------------- type Comment_Info is new Util.Beans.Basic.Readonly_Bean with record -- the comment identifier. Id : ADO.Identifier; -- the comment author's name. Author : Ada.Strings.Unbounded.Unbounded_String; -- the comment author's email. Email : Ada.Strings.Unbounded.Unbounded_String; -- the comment date. Date : Ada.Calendar.Time; -- the comment text. Comment : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get the bean attribute identified by the given name. overriding function Get_Value (From : in Comment_Info; Name : in String) return Util.Beans.Objects.Object; package Comment_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Comment_Info); package Comment_Info_Vectors renames Comment_Info_Beans.Vectors; subtype Comment_Info_List_Bean is Comment_Info_Beans.List_Bean; type Comment_Info_List_Bean_Access is access all Comment_Info_List_Bean; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Comment_Info_Vector is Comment_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Comment_List : constant ADO.Queries.Query_Definition_Access; type Comment_Bean is abstract new AWA.Comments.Models.Comment_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Comment_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the value identified by the name. overriding procedure Set_Value (Item : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private COMMENT_NAME : aliased constant String := "awa_comments"; COL_0_1_NAME : aliased constant String := "create_date"; COL_1_1_NAME : aliased constant String := "message"; COL_2_1_NAME : aliased constant String := "entity_id"; COL_3_1_NAME : aliased constant String := "id"; COL_4_1_NAME : aliased constant String := "version"; COL_5_1_NAME : aliased constant String := "entity_type"; COL_6_1_NAME : aliased constant String := "status"; COL_7_1_NAME : aliased constant String := "author_id"; COMMENT_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 8, Table => COMMENT_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access, 5 => COL_4_1_NAME'Access, 6 => COL_5_1_NAME'Access, 7 => COL_6_1_NAME'Access, 8 => COL_7_1_NAME'Access ) ); COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access := COMMENT_DEF'Access; Null_Comment : constant Comment_Ref := Comment_Ref'(ADO.Objects.Object_Ref with others => <>); type Comment_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access) with record Create_Date : Ada.Calendar.Time; Message : Ada.Strings.Unbounded.Unbounded_String; Entity_Id : ADO.Identifier; Version : Integer; Entity_Type : ADO.Entity_Type; Status : Status_Type; Author : AWA.Users.Models.User_Ref; end record; type Comment_Access is access all Comment_Impl; overriding procedure Destroy (Object : access Comment_Impl); overriding procedure Find (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Comment_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Comment_Ref'Class; Impl : out Comment_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "comment-queries.xml", Sha1 => "23485D2C3F50D233CB8D52A2414B417F4296B51A"); package Def_Commentinfo_Comment_List is new ADO.Queries.Loaders.Query (Name => "comment-list", File => File_1.File'Access); Query_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_Comment_List.Query'Access; end AWA.Comments.Models;
----------------------------------------------------------------------- -- AWA.Comments.Models -- AWA.Comments.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- pragma Warnings (Off, "unit * is not referenced"); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Objects.Enums; with Util.Beans.Basic.Lists; with AWA.Users.Models; with Util.Beans.Methods; pragma Warnings (On, "unit * is not referenced"); package AWA.Comments.Models is -- -------------------- -- The status type defines whether the comment is visible or not. -- The comment can be put in the COMMENT_WAITING state so that -- it is not immediately visible. It must be put in the COMMENT_PUBLISHED -- state to be visible. -- -------------------- type Status_Type is (COMMENT_PUBLISHED, COMMENT_WAITING, COMMENT_SPAM, COMMENT_BLOCKED, COMMENT_ARCHIVED); for Status_Type use (COMMENT_PUBLISHED => 0, COMMENT_WAITING => 1, COMMENT_SPAM => 2, COMMENT_BLOCKED => 3, COMMENT_ARCHIVED => 4); package Status_Type_Objects is new Util.Beans.Objects.Enums (Status_Type); type Comment_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The Comment table records a user comment associated with a database entity. -- The comment can be associated with any other database record. -- -------------------- -- Create an object key for Comment. function Comment_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Comment from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Comment_Key (Id : in String) return ADO.Objects.Object_Key; Null_Comment : constant Comment_Ref; function "=" (Left, Right : Comment_Ref'Class) return Boolean; -- Set the comment publication date procedure Set_Create_Date (Object : in out Comment_Ref; Value : in Ada.Calendar.Time); -- Get the comment publication date function Get_Create_Date (Object : in Comment_Ref) return Ada.Calendar.Time; -- Set the comment message. procedure Set_Message (Object : in out Comment_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Message (Object : in out Comment_Ref; Value : in String); -- Get the comment message. function Get_Message (Object : in Comment_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Message (Object : in Comment_Ref) return String; -- Set the entity identifier to which this comment is associated procedure Set_Entity_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the entity identifier to which this comment is associated function Get_Entity_Id (Object : in Comment_Ref) return ADO.Identifier; -- Set the comment identifier procedure Set_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the comment identifier function Get_Id (Object : in Comment_Ref) return ADO.Identifier; -- Get the optimistic lock version. function Get_Version (Object : in Comment_Ref) return Integer; -- Set the entity type that identifies the table to which the comment is associated. procedure Set_Entity_Type (Object : in out Comment_Ref; Value : in ADO.Entity_Type); -- Get the entity type that identifies the table to which the comment is associated. function Get_Entity_Type (Object : in Comment_Ref) return ADO.Entity_Type; -- Set the comment status to decide whether the comment is visible (published) or not. procedure Set_Status (Object : in out Comment_Ref; Value : in Status_Type); -- Get the comment status to decide whether the comment is visible (published) or not. function Get_Status (Object : in Comment_Ref) return Status_Type; -- procedure Set_Author (Object : in out Comment_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Author (Object : in Comment_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Comment_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Comment_Ref); -- Copy of the object. procedure Copy (Object : in Comment_Ref; Into : in out Comment_Ref); -- -------------------- -- The comment information. -- -------------------- type Comment_Info is new Util.Beans.Basic.Readonly_Bean with record -- the comment identifier. Id : ADO.Identifier; -- the comment author's name. Author : Ada.Strings.Unbounded.Unbounded_String; -- the comment author's email. Email : Ada.Strings.Unbounded.Unbounded_String; -- the comment date. Date : Ada.Calendar.Time; -- the comment text. Comment : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get the bean attribute identified by the given name. overriding function Get_Value (From : in Comment_Info; Name : in String) return Util.Beans.Objects.Object; package Comment_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Comment_Info); package Comment_Info_Vectors renames Comment_Info_Beans.Vectors; subtype Comment_Info_List_Bean is Comment_Info_Beans.List_Bean; type Comment_Info_List_Bean_Access is access all Comment_Info_List_Bean; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Comment_Info_Vector is Comment_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Comment_List : constant ADO.Queries.Query_Definition_Access; type Comment_Bean is abstract new AWA.Comments.Models.Comment_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Comment_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the value identified by the name. overriding procedure Set_Value (Item : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private COMMENT_NAME : aliased constant String := "awa_comment"; COL_0_1_NAME : aliased constant String := "create_date"; COL_1_1_NAME : aliased constant String := "message"; COL_2_1_NAME : aliased constant String := "entity_id"; COL_3_1_NAME : aliased constant String := "id"; COL_4_1_NAME : aliased constant String := "version"; COL_5_1_NAME : aliased constant String := "entity_type"; COL_6_1_NAME : aliased constant String := "status"; COL_7_1_NAME : aliased constant String := "author_id"; COMMENT_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 8, Table => COMMENT_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access, 5 => COL_4_1_NAME'Access, 6 => COL_5_1_NAME'Access, 7 => COL_6_1_NAME'Access, 8 => COL_7_1_NAME'Access ) ); COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access := COMMENT_DEF'Access; Null_Comment : constant Comment_Ref := Comment_Ref'(ADO.Objects.Object_Ref with others => <>); type Comment_Impl is new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access) with record Create_Date : Ada.Calendar.Time; Message : Ada.Strings.Unbounded.Unbounded_String; Entity_Id : ADO.Identifier; Version : Integer; Entity_Type : ADO.Entity_Type; Status : Status_Type; Author : AWA.Users.Models.User_Ref; end record; type Comment_Access is access all Comment_Impl; overriding procedure Destroy (Object : access Comment_Impl); overriding procedure Find (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Comment_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Comment_Ref'Class; Impl : out Comment_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "comment-queries.xml", Sha1 => "23485D2C3F50D233CB8D52A2414B417F4296B51A"); package Def_Commentinfo_Comment_List is new ADO.Queries.Loaders.Query (Name => "comment-list", File => File_1.File'Access); Query_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_Comment_List.Query'Access; end AWA.Comments.Models;
Rebuild the model files (rename table awa_comment)
Rebuild the model files (rename table awa_comment)
Ada
apache-2.0
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
13bb9f7ab00c23905f7880fe8919aba14ca9e165
src/asf-beans.ads
src/asf-beans.ads
----------------------------------------------------------------------- -- asf.beans -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Refs; with EL.Beans; with EL.Contexts; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; private with Ada.Strings.Unbounded.Hash; -- The <b>ASF.Beans</b> package is a registry for creating request, session -- and application beans. -- -- First, an application or a module registers in a class factory the class -- of objects that can be created. Each class is represented by a <b>Class_Binding</b> -- interface that allows to create instances of the given class. Each class -- is associated with a unique name in the class factory (ie, the class name). -- This step is done when the application or module is initialized. -- -- Second, a set of application configuration files define the runtime bean objects -- that can be created automatically when a request is processed. Each runtime bean -- object is associated with a bean name, a bean type identifying the class of object, -- and a scope that identifies the lifespan of the object. -- -- When a request is processed and a bean must be created, the bean factory is -- searched to find a the object class and object scope (a <b>Bean_Binding</b>). -- The <b>Class_Binding</b> associated with the <b>Bean_Binding</b> is then used -- to create the object. package ASF.Beans is -- Defines the scope of the bean instance. type Scope_Type is ( -- Application scope means the bean is shared by all sessions and requests APPLICATION_SCOPE, -- Session scope means the bean is created one for each session. SESSION_SCOPE, -- Request scope means the bean is created for each request REQUEST_SCOPE, ANY_SCOPE); -- ------------------------------ -- Class Binding -- ------------------------------ -- The <b>Class_Binding</b> provides an operation to create objects of a given class. type Class_Binding is abstract new Util.Refs.Ref_Entity with null record; type Class_Binding_Access is access all Class_Binding'Class; procedure Create (Factory : in Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is abstract; -- Simplified bean creation. A <b>Create_Bean_Access</b> function can be registered -- as a simplified class binding to create bean instances. type Create_Bean_Access is access function return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Bean initialization -- ------------------------------ -- After a bean object is created, it can be initialized with a set of values defined -- by the <b>EL.Beans.Param_Value</b> type which holds the bean property name as well -- as an EL expression that will be evaluated to get the property value. type Parameter_Bean is new Util.Refs.Ref_Entity with record Params : EL.Beans.Param_Vectors.Vector; end record; type Parameter_Bean_Access is access all Parameter_Bean; package Parameter_Bean_Ref is new Util.Refs.Indefinite_References (Element_Type => Parameter_Bean, Element_Access => Parameter_Bean_Access); -- ------------------------------ -- Bean Factory -- ------------------------------ -- The registry maintains a list of creation bindings which allow to create -- a bean object of a particular type. type Bean_Factory is limited private; -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Handler : in Create_Bean_Access); -- Register all the definitions from a factory to a main factory. procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Create a bean by using the create operation registered for the name procedure Create (Factory : in Bean_Factory; 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); private use Ada.Strings.Unbounded; package Class_Binding_Ref is new Util.Refs.Indefinite_References (Element_Type => Class_Binding'Class, Element_Access => Class_Binding_Access); package Registry_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Class_Binding_Ref.Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => Class_Binding_Ref."="); -- ------------------------------ -- Default class binding record -- ------------------------------ type Default_Class_Binding is new Class_Binding with record Create : Create_Bean_Access; end record; type Default_Class_Binding_Access is access all Default_Class_Binding'Class; -- Create a bean by using the registered create function. procedure Create (Factory : in Default_Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access); type Bean_Binding is record Scope : Scope_Type; Create : Class_Binding_Ref.Ref; Params : Parameter_Bean_Ref.Ref; end record; package Bean_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Bean_Binding, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Bean_Factory is limited record Registry : Registry_Maps.Map; Map : Bean_Maps.Map; end record; end ASF.Beans;
----------------------------------------------------------------------- -- asf.beans -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Refs; with EL.Beans; with EL.Contexts; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; private with Ada.Strings.Unbounded.Hash; -- The <b>ASF.Beans</b> package is a registry for creating request, session -- and application beans. -- -- First, an application or a module registers in a class factory the class -- of objects that can be created. Each class is represented by a <b>Class_Binding</b> -- interface that allows to create instances of the given class. Each class -- is associated with a unique name in the class factory (ie, the class name). -- This step is done when the application or module is initialized. -- -- Second, a set of application configuration files define the runtime bean objects -- that can be created automatically when a request is processed. Each runtime bean -- object is associated with a bean name, a bean type identifying the class of object, -- and a scope that identifies the lifespan of the object. -- -- When a request is processed and a bean must be created, the bean factory is -- searched to find a the object class and object scope (a <b>Bean_Binding</b>). -- The <b>Class_Binding</b> associated with the <b>Bean_Binding</b> is then used -- to create the object. package ASF.Beans is -- Defines the scope of the bean instance. type Scope_Type is ( -- Application scope means the bean is shared by all sessions and requests APPLICATION_SCOPE, -- Session scope means the bean is created one for each session. SESSION_SCOPE, -- Request scope means the bean is created for each request REQUEST_SCOPE, ANY_SCOPE); -- ------------------------------ -- Class Binding -- ------------------------------ -- The <b>Class_Binding</b> provides an operation to create objects of a given class. type Class_Binding is abstract new Util.Refs.Ref_Entity with null record; type Class_Binding_Access is access all Class_Binding'Class; procedure Create (Factory : in Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is abstract; -- Simplified bean creation. A <b>Create_Bean_Access</b> function can be registered -- as a simplified class binding to create bean instances. type Create_Bean_Access is access function return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Bean initialization -- ------------------------------ -- After a bean object is created, it can be initialized with a set of values defined -- by the <b>EL.Beans.Param_Value</b> type which holds the bean property name as well -- as an EL expression that will be evaluated to get the property value. type Parameter_Bean is new Util.Refs.Ref_Entity with record Params : EL.Beans.Param_Vectors.Vector; end record; type Parameter_Bean_Access is access all Parameter_Bean; package Parameter_Bean_Ref is new Util.Refs.Indefinite_References (Element_Type => Parameter_Bean, Element_Access => Parameter_Bean_Access); -- ------------------------------ -- Bean Factory -- ------------------------------ -- The registry maintains a list of creation bindings which allow to create -- a bean object of a particular type. type Bean_Factory is limited private; -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access); -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Handler : in Create_Bean_Access); -- Register all the definitions from a factory to a main factory. procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE); -- Create a bean by using the create operation registered for the name procedure Create (Factory : in Bean_Factory; 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); -- Create a map bean object that allows to associate name/value pairs in a bean. function Create_Map_Bean return Util.Beans.Basic.Readonly_Bean_Access; private use Ada.Strings.Unbounded; package Class_Binding_Ref is new Util.Refs.Indefinite_References (Element_Type => Class_Binding'Class, Element_Access => Class_Binding_Access); package Registry_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Class_Binding_Ref.Ref, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => Class_Binding_Ref."="); -- ------------------------------ -- Default class binding record -- ------------------------------ type Default_Class_Binding is new Class_Binding with record Create : Create_Bean_Access; end record; type Default_Class_Binding_Access is access all Default_Class_Binding'Class; -- Create a bean by using the registered create function. procedure Create (Factory : in Default_Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access); type Bean_Binding is record Scope : Scope_Type; Create : Class_Binding_Ref.Ref; Params : Parameter_Bean_Ref.Ref; end record; package Bean_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Bean_Binding, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); type Bean_Factory is limited record Registry : Registry_Maps.Map; Map : Bean_Maps.Map; end record; end ASF.Beans;
Declare Create_Map_Bean function
Declare Create_Map_Bean function
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
bb81b9f6217cf411412e1965b01946d11574a2aa
awa/plugins/awa-wikis/regtests/awa-wikis-tests.ads
awa/plugins/awa-wikis/regtests/awa-wikis-tests.ads
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with Ada.Strings.Unbounded; package AWA.Wikis.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Wiki_Ident : Ada.Strings.Unbounded.Unbounded_String; Page_Ident : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the wiki page as anonymous users. procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String); -- Verify that the wiki lists contain the given page. procedure Verify_List_Contains (T : in out Test; Page : in String); -- Test access to the wiki as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of wiki space and page by simulating web requests. procedure Test_Create_Wiki (T : in out Test); end AWA.Wikis.Tests;
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with AWA.Tests; with Ada.Strings.Unbounded; package AWA.Wikis.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new AWA.Tests.Test with record Wiki_Ident : Ada.Strings.Unbounded.Unbounded_String; Page_Ident : Ada.Strings.Unbounded.Unbounded_String; end record; -- Get some access on the wiki page as anonymous users. procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String); -- Verify that the wiki lists contain the given page. procedure Verify_List_Contains (T : in out Test; Page : in String); -- Test access to the wiki as anonymous user. procedure Test_Anonymous_Access (T : in out Test); -- Test creation of wiki space and page by simulating web requests. procedure Test_Create_Wiki (T : in out Test); -- Test getting a wiki page which does not exist. procedure Test_Missing_Page (T : in out Test); end AWA.Wikis.Tests;
Declare Test_Missing_Page procedure
Declare Test_Missing_Page procedure
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
2300492af98a72c9ca5bc67f4efe174a63af82e5
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info) is begin Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
Implement the Add_Region procedure
Implement the Add_Region procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
c82bfb77143d45d6eeb578a68084972333cd25e8
src/asf-components-core-views.adb
src/asf-components-core-views.adb
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- 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.Unchecked_Deallocation; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; with ASF.Applications.Main; package body ASF.Components.Core.Views is use ASF; use EL.Objects; use type Base.UIComponent_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. -- ------------------------------ function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale is use type Util.Locales.Locale; begin if UI.Locale /= Util.Locales.NULL_LOCALE then return UI.Locale; end if; declare Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Name => "locale", Context => Context); begin -- If the root view does not specify any locale, calculate it from the request. if Util.Beans.Objects.Is_Null (Value) then return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; -- Resolve the locale. If it is not valid, calculate it from the request. declare Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin if Locale /= Util.Locales.NULL_LOCALE then return Locale; else return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; end; end; end Get_Locale; -- ------------------------------ -- Set the locale to be used when rendering messages in the view. -- ------------------------------ procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale) is begin UI.Locale := Locale; end Set_Locale; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); if UI.Left_Tree /= null then UI.Left_Tree.Encode_All (Context); end if; end Encode_Begin; -- ------------------------------ -- Encode the end of the view. -- ------------------------------ overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class) is begin if UI.Right_Tree /= null then UI.Right_Tree.Encode_All (Context); end if; end Encode_End; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then UIView'Class (Parent.all).Broadcast (Phase, Context); else -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end if; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Left_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Left_Tree := Tree; end Set_Before_View; -- ------------------------------ -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Right_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Right_Tree := Tree; end Set_After_View; -- ------------------------------ -- Finalize the object. -- ------------------------------ overriding procedure Finalize (UI : in out UIView) is procedure Free is new Ada.Unchecked_Deallocation (Object => Base.UIComponent'Class, Name => Base.UIComponent_Access); begin Free (UI.Left_Tree); Free (UI.Right_Tree); Base.UIComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Get the root component. -- ------------------------------ function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access is Result : Base.UIComponent_Access := UI.Get_Parent; Parent : Base.UIComponent_Access := Result.Get_Parent; begin while Parent /= null loop Result := Parent; Parent := Parent.Get_Parent; end loop; return Result; end Get_Root; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_End (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- 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.Unchecked_Deallocation; with ASF.Events.Phases; with ASF.Components.Base; with ASF.Events.Faces.Actions; with ASF.Applications.Main; package body ASF.Components.Core.Views is use ASF; use EL.Objects; use type Base.UIComponent_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Events.Faces.Faces_Event'Class, Name => Faces_Event_Access); -- ------------------------------ -- Get the content type returned by the view. -- ------------------------------ function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String is begin if Util.Beans.Objects.Is_Null (UI.Content_Type) then return UI.Get_Attribute (Name => "contentType", Context => Context); else return Util.Beans.Objects.To_String (UI.Content_Type); end if; end Get_Content_Type; -- ------------------------------ -- Set the content type returned by the view. -- ------------------------------ procedure Set_Content_Type (UI : in out UIView; Value : in String) is begin UI.Content_Type := Util.Beans.Objects.To_Object (Value); end Set_Content_Type; -- ------------------------------ -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. -- ------------------------------ function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale is use type Util.Locales.Locale; begin if UI.Locale /= Util.Locales.NULL_LOCALE then return UI.Locale; end if; declare Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Name => "locale", Context => Context); begin -- If the root view does not specify any locale, calculate it from the request. if Util.Beans.Objects.Is_Null (Value) then return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; -- Resolve the locale. If it is not valid, calculate it from the request. declare Name : constant String := Util.Beans.Objects.To_String (Value); Locale : constant Util.Locales.Locale := Util.Locales.Get_Locale (Name); begin if Locale /= Util.Locales.NULL_LOCALE then return Locale; else return Context.Get_Application.Get_View_Handler.Calculate_Locale (Context); end if; end; end; end Get_Locale; -- ------------------------------ -- Set the locale to be used when rendering messages in the view. -- ------------------------------ procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale) is begin UI.Locale := Locale; end Set_Locale; -- ------------------------------ -- Encode the begining of the view. Set the response content type. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class) is Content_Type : constant String := UI.Get_Content_Type (Context => Context); begin Context.Get_Response.Set_Content_Type (Content_Type); if UI.Left_Tree /= null then UI.Left_Tree.Encode_All (Context); end if; end Encode_Begin; -- ------------------------------ -- Encode the end of the view. -- ------------------------------ overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class) is begin if UI.Right_Tree /= null then UI.Right_Tree.Encode_All (Context); end if; end Encode_End; -- ------------------------------ -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Decodes (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.APPLY_REQUEST_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Decodes; -- ------------------------------ -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Validators (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.PROCESS_VALIDATION, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Validators; -- ------------------------------ -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> -- ------------------------------ overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class) is begin Base.UIComponent (UI).Process_Updates (Context); -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.UPDATE_MODEL_VALUES, Context); -- Drop other events if the response is to be returned. if Context.Get_Render_Response or Context.Get_Response_Completed then UIView'Class (UI).Clear_Events; end if; end Process_Updates; -- ------------------------------ -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. -- ------------------------------ procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class) is begin -- Dispatch events queued for this phase. UIView'Class (UI).Broadcast (ASF.Events.Phases.INVOKE_APPLICATION, Context); end Process_Application; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class) is Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then Parent.Queue_Event (Event); else UI.Phase_Events (Event.Get_Phase).Append (Event.all'Access); end if; end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is Pos : Natural := 0; -- Broadcast the event to the component's listeners -- and free that event. procedure Broadcast (Ev : in out Faces_Event_Access); procedure Broadcast (Ev : in out Faces_Event_Access) is begin if Ev /= null then declare C : constant Base.UIComponent_Access := Ev.Get_Component; begin C.Broadcast (Ev, Context); end; Free (Ev); end if; end Broadcast; Parent : constant Base.UIComponent_Access := UI.Get_Parent; begin if Parent /= null then UIView'Class (Parent.all).Broadcast (Phase, Context); else -- Dispatch events in the order in which they were queued. -- More events could be queued as a result of the dispatch. -- After dispatching an event, it is freed but not removed -- from the event queue (the access will be cleared). loop exit when Pos > UI.Phase_Events (Phase).Last_Index; UI.Phase_Events (Phase).Update_Element (Pos, Broadcast'Access); Pos := Pos + 1; end loop; -- Now, clear the queue. UI.Phase_Events (Phase).Clear; end if; end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ procedure Clear_Events (UI : in out UIView) is begin for Phase in UI.Phase_Events'Range loop for I in 0 .. UI.Phase_Events (Phase).Last_Index loop declare Ev : Faces_Event_Access := UI.Phase_Events (Phase).Element (I); begin Free (Ev); end; end loop; UI.Phase_Events (Phase).Clear; end loop; end Clear_Events; -- ------------------------------ -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Left_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Left_Tree := Tree; end Set_Before_View; -- ------------------------------ -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. -- ------------------------------ procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access) is begin if UI.Right_Tree /= null then UI.Log_Error ("Set_Before_View called while there is a tree"); end if; UI.Right_Tree := Tree; end Set_After_View; -- ------------------------------ -- Finalize the object. -- ------------------------------ overriding procedure Finalize (UI : in out UIView) is procedure Free is new Ada.Unchecked_Deallocation (Object => Base.UIComponent'Class, Name => Base.UIComponent_Access); begin Free (UI.Left_Tree); Free (UI.Right_Tree); Base.UIComponent (UI).Finalize; end Finalize; -- ------------------------------ -- Set the metadata facet on the UIView component. -- ------------------------------ procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin if UI.Meta /= null then UI.Log_Error ("A <f:metadata> component was already registered."); -- Delete (UI.Meta); end if; Meta.Root := UI'Unchecked_Access; UI.Meta := Meta; UI.Add_Facet (METADATA_FACET_NAME, Meta.all'Access, Tag); end Set_Metadata; -- ------------------------------ -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. -- ------------------------------ overriding function Get_Parameter (UI : in UIViewParameter; Context : in Faces_Context'Class) return String is Name : constant String := UI.Get_Attribute ("name", Context); begin if Name'Length > 0 then return Context.Get_Parameter (Name); else return Html.Forms.UIInput (UI).Get_Parameter (Context); end if; end Get_Parameter; -- ------------------------------ -- Decode the request and prepare for the execution for the view action. -- ------------------------------ overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; begin ASF.Events.Faces.Actions.Post_Event (UI => UI, Method => UI.Get_Action_Expression (Context)); exception when EL.Expressions.Invalid_Expression => null; end; end Process_Decodes; -- ------------------------------ -- Get the root component. -- ------------------------------ function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access is Result : Base.UIComponent_Access := UI.Get_Parent; Parent : Base.UIComponent_Access := Result.Get_Parent; begin while Parent /= null loop Result := Parent; Parent := Parent.Get_Parent; end loop; return Result; end Get_Root; -- ------------------------------ -- Start encoding the UIComponent. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Begin (Context); end Encode_Begin; -- ------------------------------ -- Encode the children of this component. -- ------------------------------ overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_Children (Context); end Encode_Children; -- ------------------------------ -- Finish encoding the component. -- ------------------------------ overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class) is begin UI.Get_Root.Encode_End (Context); end Encode_End; -- ------------------------------ -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. -- ------------------------------ overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class) is begin UI.Root.Queue_Event (Event); end Queue_Event; -- ------------------------------ -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. -- ------------------------------ overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class) is begin UI.Root.Broadcast (Phase, Context); end Broadcast; -- ------------------------------ -- Clear the events that were queued. -- ------------------------------ overriding procedure Clear_Events (UI : in out UIViewMetaData) is begin UI.Root.Clear_Events; end Clear_Events; end ASF.Components.Core.Views;
Implement the Get_Parameter function to support the <f:viewParam> name attribute
Implement the Get_Parameter function to support the <f:viewParam> name attribute
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
8821fd490aaf687d43eb36323c3af7a7200e21e9
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "42"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; synth_version_major : constant String := "1"; synth_version_minor : constant String := "43"; copyright_years : constant String := "2015-2016"; host_localbase : constant String := "/usr/local"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; jobs_per_cpu : constant := 2; type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; end Definitions;
Bump to version v1.43
Bump to version v1.43
Ada
isc
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
28ae0b975f18cb75fbf8f408724c172caeae9dd5
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "13"; copyright_years : constant String := "2015-2018"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.2.0"; previous_compiler : constant String := "7.3.0"; binutils_version : constant String := "2.31.1"; previous_binutils : constant String := "2.30"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "1"; raven_version_minor : constant String := "14"; copyright_years : constant String := "2015-2018"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.28"; default_pgsql : constant String := "10"; default_php : constant String := "7.2"; default_python3 : constant String := "3.7"; default_ruby : constant String := "2.5"; default_tcltk : constant String := "8.6"; default_firebird : constant String := "2.5"; default_compiler : constant String := "gcc8"; compiler_version : constant String := "8.2.0"; previous_compiler : constant String := "7.3.0"; binutils_version : constant String := "2.31.1"; previous_binutils : constant String := "2.30"; arc_ext : constant String := ".tzst"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; raven_var : constant String := "/var/ravenports"; host_pkg8 : constant String := host_localbase & "/sbin/pkg-static"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Bump version for php/postgresql changes
Bump version for php/postgresql changes
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm